Python 3.X: nonlocal support in eval/exec?

2011-08-11 Thread Paddy
We can access nonlocal variables in a function, but if we were to eval/
exec the function we cannot set up a nested stack of evironment dicts.
We are limited to just two: global and local.

How about eval/exec take a new env argument that is a nested
dictionary whose outer level corresponds to locals, and which has a
__up__ value which is the next outer level environment dict. The
outermost level of the nested dictionary would correspond to the
global level?

I haven't given much thought to my suggested solution - I just didn't
want to leave a possible solution out. The major point is that there
seems to be no support for nonlocal in eval/exec (unless, trivially,
nonlocal==global).

- Paddy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.X: nonlocal support in eval/exec?

2011-08-11 Thread Paddy
On Aug 11, 8:48 am, Terry Reedy  wrote:
> On 8/11/2011 3:19 AM, Paddy wrote:
>
> > We can access nonlocal variables in a function, but if we were to eval/
> > exec the function we cannot set up a nested stack of evironment dicts.
> > We are limited to just two: global and local.
>
> Right. That was and is Python's execution model.
> Note that when you exec code, including a function call, the locals
> passed is the local context in which the code is executed. It is not the
> locals of any particular function called by the exec-ed code.
>
> If you exec a function that is a closure, the closure or non-local
> objects come with the function. A 'stack of dicts' has nothing to do
> with how function and nested funcs operate.
>
> --
> Terry Jan Reedy

Thanks Terry.
-- 
http://mail.python.org/mailman/listinfo/python-list


functools.partial doesn't work without using named parameter

2011-03-24 Thread Paddy
Hi, I just found the following oddity where for function fsf1 I am forced to 
use a named parameter for correct evaluation and was wondering why it doesn't 
work, yet the example from the docs of wrapping int to create basetwo doesn't 
need this?
The example:

>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo('10010')
18
>>> 
>>> def fs(f, s): return [f(value) for value in s]

>>> def f1(value): return value * 2

>>> s = [0, 1, 2, 3]
>>> fs(f1, s)
[0, 2, 4, 6]
>>> 
>>> fsf1 = partial(fs, f=f1)
>>> fsf1(s)
Traceback (most recent call last):
  File "", line 1, in 
fsf1(s)
TypeError: fs() got multiple values for keyword argument 'f'
>>> # BUT
>>> fsf1(s=s)
[0, 2, 4, 6]
>>> 

Would someone help?

- Thanks in advance, Paddy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: functools.partial doesn't work without using named parameter

2011-03-24 Thread Paddy
P.S: Python 3.2!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: functools.partial doesn't work without using named parameter

2011-03-25 Thread Paddy
Thanks Ian, Benjamin, and Steven.

I now know why it works as it does.

Thinking about it a little more, Is it reasonable to *expect* partial acts as 
it does, rather than this way being an implementation convenience? (That was 
written as a straight question not in any way as a dig).

I had thought that partial had enough information to, and would in fact, remove 
named parameter f from the signature of fsf1 returning something that could be 
called that is the equivalent of:

def fsf1_( s ): ...

I accept that that is not done, but would welcome discussion on if my 
expectation above was reasonable. 

Thanks guys :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: functools.partial doesn't work without using named parameter

2011-03-25 Thread Paddy
Aha!

Thanks Ian for this new snippet. It is what I will use for my current example. 
(But please see my third posting on this too).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Testing for performance regressions

2011-04-04 Thread Paddy
In an extended case when you try and capture how a function works over a range 
of inputs, you might want to not assume some relationship between input size 
and time, as this mnight limit your ability to change algorithms and still have 
acceptable performance. 

I.e. instead of this:

input_range = (MIN, AVERAGE, MAX)
for i in inpute_range:
..baseline = Timer(simple_func(i)).timeit()
..time_taken = Timer(my_func(i)).timeit()
..assert time_taken <= simple_relation(i) * baseline

It might be better to do this:

input_range = (MIN_R, AVERAGE_R, MAX_R)
time_ranges = (MIN_T, AVERAGE_T, MAX_T)
for i,t in zip(inpute_range, time_ranges):
..baseline = Timer(simple_func(i)).timeit()
..time_taken = Timer(my_func(i)).timeit()
..assert time_taken <= t * baseline

This comes from electronic circuit design where designs must be proven to work 
over a range for different values for example voltage ranges and temperature 
ranges. 

The action of the function being timed might not be simple, for example if 
my_func swapped algorithms depending on its input to favour the average case. 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Guido rethinking removal of cmp from sort method

2011-04-04 Thread Paddy
On Tuesday, April 5, 2011 2:16:07 AM UTC+1, harrismh777 wrote:
> Steven D'Aprano wrote:
> > I prefer to consider Python 2.7 and Python 3.x as different dialects of
> > the same language. There are a very few handful of incompatibilities,
> > most of which can be automatically resolved by the 2to3 fixers.
> 
> Yes, I am actually finding this to be consistent with my experience of 
> trying to come up to speed with 3.2.  I have been relieved to find that 
> less has changed than the fear-mongering and bickering was leading me to 
> believe.
> 
> Another item that would be nice as an IDLE enhancement would be a menu 
> option that applies the fixers (either direction depending on version 
> 2.7 <--> 3.2) right in the IDE. Entries that could not be fixed could be 
> flagged for manual update.
> 
> If there are good tools for app developers to use to make the transition 
> smoother then the development community won't get their ear chewed off 
> so ragged, I'm supposing.

Hats off and three cheers to the developers and python community as a whole, as 
some are down to sugesting easier access to 2<->3 rather than OMG! How do I 
port!!

Now that is an excellent sign that Python works.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: User-defined augmented assignment

2005-09-29 Thread Paddy
I thought along these lines:
  It is an augmented ASSIGNMENT. (It even has an equals sign in it).
  tuples are immutable so you should not be able to assign to one of
its elements.

 - So there is no problem for me - I shouldn't be messing with an
element of an
immutable type!

- Cheers, Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some set operators

2005-10-16 Thread Paddy
Hi Bearophile,
Nah, you don't want to change 'em. I can remember 'em just fine :-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can a cut-down Python still be Python?

2005-10-17 Thread Paddy
If you mean missing out some of the libraries then that would be
different to missing out core functionality sucjh as generators or list
expressions,...

In general, if the end task is not to present the world with a new
programming language then it's usually best to choose from the
available, supported languages rather than creating your own.

Maybe you should take a look at, for example, Lua:
  http://www.lua.org/

But if the trail leads back to Python, then go for it :-)

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help: Quick way to test if value lies within a list of lists of ranges?

2005-10-27 Thread Paddy
Would this help?


'''
>>> pp(name2ranges)
{'a': [[5, 12], [27, 89], [120, 137]],
 'b': [[6, 23], [26, 84], [200, 222]],
 'c': [[2, 22], [47, 60], [67, 122]]}
>>> names4val(28)
['a', 'b']
>>> names4val(11)
['a', 'c', 'b']
>>> names4val(145)
[]
>>>

'''
from pprint import pprint as pp

name2ranges = {
  'a': [[48,60], [27,89], [5,12], [120,137]],
  'b': [[78,84], [26,79], [200,222], [6,23], [72,74]],
  'c': [[67,122],[2,22], [47,60]]
  }

for name, ranges in name2ranges.iteritems():
  # sort ranges
  name2ranges[name].sort()
  # Coalesce overlapping ranges.
  # If the max of one range is >= the min of the next range then
  # the adjacent ranges are combined
  ln = len(ranges)
  newranges = []
  i = 0
  while i< ln:
mn,mx = ranges[i]
j = i+1
while j< ln and ranges[j][0] <=mx:
  mx = max(mx, ranges[j][1])
  j += 1
newranges.append([mn,mx])
i = j
  name2ranges[name] = newranges

def names4val(val):
  " find the names whose ranges intersect the value"
  from bisect import bisect_left
  names = []
  for name,ranges in name2ranges.iteritems():
bs = bisect_left(ranges, [val,val])
if (bs and ranges[bs-1][0] <= val <= ranges[bs-1][1] ) or (
bs http://mail.python.org/mailman/listinfo/python-list


Re: MSH (shell)

2005-10-28 Thread Paddy
Thanks, I'm enjoying reading the article.
So far I noticed how their select functionality is similar to our
comprehensions, but can also take a statement block. ( no wars please
;-).

I liked the tabular output format for lists of similar items, with the
automatic headings being displayed, e.g:
msh> get-childitem | select name, extension, {
  if ($_.LastWriteTime.year -lt 2004) { "old file" }
  else { "new file" }
}

Name   Extension  if
($_.LastWriteTime.year...
   -
-
examples.txt   .txt   new file
output1.html   .html  old file
output2.html   .html  old file
somefile.doc   .doc   new file


I tend to avoid xml but their xml example below was succinct and
relatively painless. Do python libraries allow a similarly readable
version of their:

  msh>   $x = [xml]"Albert"
msh> $x.zoo.animal

kindname

monkey  Albert

Their "Extract the title and author elements from every item in the
rss.channel tag" example is also impressive.

Looks like an innovative new shell.

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonising the vim (e.g. syntax popups)

2005-11-09 Thread Paddy
Hi,
I am using gvim 6.4 which has Python colorising, and
The menu tools->folding->fold method->indent

:help folding
May give you more info.

Cheers, Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Death to tuples!

2005-11-28 Thread Paddy
I would consider
 t =  ([1,2], [3,4])
to be assigning a tuple with two list elements to t.
The inner lists will be mutable but I did not know you could change the
outer tuple and still have the same tuple object.

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Equivalent to Text::Autoformat

2005-12-03 Thread Paddy
Google is your freind.
Try searching for:
  python text wrapping

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-29 Thread Paddy
Joseph Garvin wrote:
  'm curious -- what is everyone's favorite trick from a non-python
  language? And -- why isn't it in Python?

I use constraints programming at work, Check out "System Verilog"  or
OZ/Mozart.

It would be great if this style of programming could be added to
Python.

It is a declarative programming style
(http://en.wikipedia.org/wiki/Declarative_programming), in which you
can state what discrete values constrained values can take , say in a
list. Give a set of functions that must be true for the variables then
sit back and generate one or many sets of variable values that fit the
constraints.

The OZ homepage has an example for solving the eight queens problem:

http://www.mozart-oz.org/documentation/fdt/node25.html#section.scripts.queens

My use would be for testing. In the electronic design automation
fields, there are several proprietary languages with this feature, here
is an example written in Cadence's Specman 'e' language:
  http://www.asic-world.com/specman/specman_one_day2.html


Cheers, Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-29 Thread Paddy
Sadly, its not a solution that I'm after, but a particular toolkit that
can be used for solving that type of problem.

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A replacement for lambda

2005-07-30 Thread Paddy
Christopher Subich <[EMAIL PROTECTED]> writes:
> Basically, I'd rewrite the Python grammar such that:
> lambda_form ::= "<" expression "with" parameter_list ">"

I do prefer my parameter list to come before the expression. It would
remain consistant with simple function definitions.

- Cheers, Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Thaughts from an (almost) Lurker.

2005-07-31 Thread Paddy
Sometimes when reading c.l.p.  I mentally stand off from what I have
been reading and get an odd feeling that 'WE ARE BEING TESTED'. That
someone else is purposefully posting a near repetitive post, or obvious
flame bait etc - not for the usual reasons, but to track the dynamics
af the replies. Rather like dropping a stone in the river and watching
pythonistas return c.l.p. to its normal, helpful, and polite norm.
Fascinating.
I only hope that if thats the case, then they should post their
findings here.

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thaughts from an (almost) Lurker.

2005-07-31 Thread Paddy

L.OL :-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decline and fall of scripting languages ?

2005-08-06 Thread Paddy
Do you know anyone who has dropped LAMP for a proprietary Web solution?
Or vice versa?
Know any sys-admins that have dropped their use of scripting languages
for something else?
What are the alternatives that are supposedly driving scripting
languages out?

- I'm unconvinced.

-- 
http://mail.python.org/mailman/listinfo/python-list


Interface type checking

2005-08-10 Thread Paddy
Hi,
I read a blog entry by GVR on interfaces in which he mentioned that you
had to be able to state the type signature of, say, a function.

That got me thinking along the lines of:
  If you have some typical data, then transform it into a string
showing
  its sub-types.
  Could not a regular expression matching this string be used to check
the type signature of the data?

for example:
  >>> data = [[{'a': 1, ('b',):3.0 }, ()]]
  >>> stringrep = typeExpand(data)
  >>> stringrep
  'list:float>,tuple<>>>'
  >>> re.match(r"^list|tuple<.*>)*>>$",stringrep)
  <_sre.SRE_Match object at 0x01611F60>
  >>>

Looking at the example above, I don't think regular expression matching
is right.
Some extra syntax such as:
  typeMatcher.match(r"list|tuple<.*>)*>>", stringrep
Where this matcher is more like a parser and so does '<' '>' nested
bracket matching; changes . to mean 0 or more types (e.g: 'str'; or
'str,str...'); and allows you the shorthand of writing 'list' for
.list<.*>'.

I've done some work below on typeExpand, but I'm not fluent in a parser
module to implement typeMatcher.match quickly.

Enjoy!


#== BEGIN typeMatcher.py ==
'''
Object type Expander
'''

import types
from pprint import pprint as pp

# Map types to a type name
type2name = dict( [ (typ,name[:name.rindex('Type')].lower())
for name,typ in types.__dict__.iteritems()
  if type(typ)==types.TypeType
  and str(typ).find('=0 ]
  +[(type(set()), 'set')] )
#pp(type2name)

def typeExpand(obj):
  ' Expand an objects type'
  ty = type(obj)
  name = type2name.get(ty,'')
  if not name:
# Make up a name. So "" becomes "_type_XX_"
name = str(type(obj))
name = name.replace(' ','_')
name = name.replace('<','_')
name = name.replace('>','_')
name = name.replace("'",'')
  typeExpansionHandler = globals().get( name+'__TypeHandler', None)
  if typeExpansionHandler:
return ''.join([name, '<', typeExpansionHandler(obj), '>'])
  else:
return name

def list__TypeHandler(obj):
  ' How to expand the contents of a list/tuple'
  return ','.join([ typeExpand(ob) for ob in obj])
tuple__TypeHandler = list__TypeHandler

def dict__TypeHandler(obj):
  ' How to expand the contents of a dict'
  return ','.join([ '%s:%s' % (typeExpand(name), typeExpand(value))
for name,value in obj.iteritems()])

def match(matchExprString, typeString): pass

#== END typeMatcher.py ==

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list to tuple

2005-08-11 Thread Paddy
Try this:

>>> a,b,c = list('tab'),list('era'),list('net')
>>> a,b,c
(['t', 'a', 'b'], ['e', 'r', 'a'], ['n', 'e', 't'])
>>> tuple(((x,y,z) for x,y,z in zip(a,b,c)))
(('t', 'e', 'n'), ('a', 'r', 'e'), ('b', 'a', 't'))
>>> 

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Software bugs aren't inevitable

2005-09-12 Thread Paddy
A work colleague circulated this interesting article about reducing
software bugs by orders of magnitude:
  http://www.spectrum.ieee.org/WEBONLY/publicfeature/sep05/0905ext.html

Some methods they talk about include removing error prone and ambiguous
expressions from their ADA based language Sparc - The example they give
is on why they removed the increment operators x++, x-- .

A bit of googling shows that they have, in the past mentioned Python in
Job specs, but only as one of many languages.

I was wondering what Praxis thought of Python, and how good it would be
if a Praxis engineer gave a critique of Python as a part of a flow for
producing low bug-count software.

In this sidebar to the main article:

http://www.spectrum.ieee.org/WEBONLY/publicfeature/sep05/0905extsb1.html

It seems that they use one equation from the Z notation model and add
it as a comment to their main programming languages function definition
as a comment, then have a means of automatically testing the comment
against the function body.

This is rather like how doctest can check the test and expected result
given in a doc-string against the implementation given in the function;
indeed I wrote up such an example at work and circulated it amongst the
resident perl mongers. - Gosh it fealt good :-)

So, How do I get feedback from Praxis, Do they already read
comp.lang.py?

Cheers,  Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software bugs aren't inevitable

2005-09-14 Thread Paddy
Hmm, They seem to have reorganised things.
As I write, the main article starts here:
  http://www.spectrum.ieee.org/sep05/2164
With the sidebar here:
  http://www.spectrum.ieee.org/sep05/2164/extsb1

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software bugs aren't inevitable

2005-09-14 Thread Paddy
Thanks Giles,
I was hoping for a reply from someone close to Praxis like yourself,
but, I'm shocked when you said they use Perl as their scripting
language of choice, because I thought that with such an emphasis on
correctness and maintainability, that it would spill over into other
aspects of their flow.

Maybe they don't see scripting as part of their flow, but as merely
occasional 'duct tape'?

I did find an email address on the page you specified and have invited
Praxis to join in on this thread, or comment on Python in general.

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Oh Yes, They Are [was: Re: Software bugs aren't inevitable]

2005-09-15 Thread Paddy
Surely, (don't call me Shirley), one of the goals pf Python is to make
the Programmer more productive.
It is obvious that we can tolerate some bugs in programs, but, after
reading the article, I thought that we might have a change to here from
'the other side'.
I get the fealing that the proponents of flows such as Extreme
Programming are decreasing the bug rate compared to their previous
flows, where Praxis might be able to suggest Python methodology that
would be an increase in bug-rate compared to their internal flow, but
maybe be better than current workflows.

P.S. I like your suggestion about pycon, but I have no reply from
anyone at Praxis after emailing them yesterday.

- Cheers,  Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software bugs aren't inevitable

2005-09-16 Thread Paddy
The article states that their method calls for them to have much more
than normal access to many more people in the clients organisation than
is normal; from the CEO to the receptionist.
The specification stage can take a year without the customer seeing a
line of code.
And they deliberately "write one to throw away".

In short, they *are* aware of the human element .

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to program efficient pattern searches in a list of float numbers?

2005-09-19 Thread Paddy
How about posting example data and results?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: combining several lambda equations

2005-02-18 Thread Paddy
Steve,
Thanks for the info but I do know about that..
What I am doing is taking a set of inputted functions that don't
take arguments and programmatically analysing them and
combining them to create new functions that are further analysed.

During testing I keep the numbers low, and am only dealing with one to
two hundred equations, but real life problems could involve maybe
thousands of them., (and then I'd ptobably shift to using tuples of
ints or tuples of strings as 'handles'  or keys to
my generated functions, to convey more info on how
intermediate functions are generated).

Thanks again for the interest,
-  Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


On eval and its substitution of globals

2005-02-19 Thread Paddy
Hi,
I got tripped up on the way eval works with respect to modules and
so wrote a test.

It seems that a function carries around knowledge of the globals()
present
when it was defined. (The .func_globals attribute)?

When evaluated using eval(...) the embedded globals can be overridden
with
the one passed through the eval(...) call

If however you create a new function that calls the first then eval's
global argument is only substituted in the outer call!

TEST:
=

Python 2.4 (#2, Jan  8 2005, 20:18:03)
[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> globals().has_key('A')
False
>>> globals().has_key('B')
False
>>> def f1(): return A < B
...
>>> def z(): return f1()
...
>>> eval(f1.func_code,dict(A=1,B=2))
True
>>> eval(z.func_code,dict(A=1,B=2, f1=f1))
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 1, in z
  File "", line 1, in f1
NameError: global name 'A' is not defined
>>>

ENDTEST
===

Is there a way to do a deep substitution of the globals?

I should add that f1 is given as-is. I can modify z,
and f1 is just one of many functions given and function z
is some boolean function of the f's


Thanks, Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On eval and its substitution of globals

2005-02-22 Thread Paddy
I have had no reply so on revisiting this I thought I would re-submit
it  and point out that there is a question way down at the end :-)

Thanks.

= Original Post =
Hi,
I got tripped up on the way eval works with respect to modules and
so wrote a test.

It seems that a function carries around knowledge of the globals()
present
when it was defined. (The .func_globals attribute)?

When evaluated using eval(...) the embedded globals can be overridden
with
the one passed through the eval(...) call

If however you create a new function that calls the first then eval's
global argument is only substituted in the outer call!

TEST:
=

Python 2.4 (#2, Jan  8 2005, 20:18:03)
[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> globals().has_key('A')
False
>>> globals().has_key('B')
False
>>> def f1(): return A < B
...
>>> def z(): return f1()
...
>>> eval(f1.func_code,dict(A=1,B=2))
True
>>> eval(z.func_code,dict(A=1,B=2, f1=f1))

Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 1, in z
  File "", line 1, in f1
NameError: global name 'A' is not defined


ENDTEST
===

Is there a way to do a deep substitution of the globals?

I should add that f1 is given as-is. I can modify z,
and f1 is just one of many functions given and function z
is some boolean function of the f's

Thanks, Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On eval and its substitution of globals

2005-02-23 Thread Paddy
Thanks Kent for your reply.
I had to do as you suggest but I was thinking either it was a kludge,
and there should be a 'deep' substitution of globals, or that there was
a good reason for it to work as it does and some magician would tell
me.
Oh, the third reason could be that it was first implimented that way
and no-one has submitted a patch of course.

Could someone clue me in?

Ta,  Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On eval and its substitution of globals

2005-02-23 Thread Paddy
Leif wrote:
" If globals were deeply substituted when using eval, the program would
presumably print "42\n24", which would be far from intuitive. If you
limit the deep substitution to functions in the same module, you're
creating a confusing special case.  "

I guess I need outside opinions on what should be normal. The
documentation does not mention the case of 'nested' function calls and
so the present action could be documented but  there is still the issue
of "should there be a 'deep'  globals substitution". I have such a
need, but this is the first time I have had to consider this whole
topic.
I do in fact have the case you mention. I am writing a module that will
manipulate functions of global variables where the functions are
defined in another module.
My module will evaluate those 'other module' functions supplying the
globals itself - which works fine, the problem comes when I create
derivative functions in my module that call the original 'other module'
functions, and then try and evaluate these derivatives supplying the
globals as before. The 'correct' action that I want is for the globals
I supply to eval to be used for all functions called by the code block
as well as for the code block itself.

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to pass a parameter by reference?

2005-02-27 Thread Paddy
It is usually clearer to explicitely return values that are changed by
a function and re-assign it to the same variable,

x=something1
a = something2
def f1(s,t):
  # do something with t,
  # do something to s
  return s
a = f1(a,x)

Be aware however that you can wrap 'a' in a list for the same effect,
(but it is not as easy to read).

x=something1
aa = [something2]
def f2(ss,t):
  s= ss[0]
  # do something with t,
  # do something to s
  ss[0]=s
f2(aa,x)
a=aa[0]

-- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why tuple with one item is no tuple

2005-03-15 Thread Paddy
Hmm,
going 'the other way', you are allowed an extra , but you can't have
(,) as the empty tuple.:

>>> (1,2,)
(1, 2)
>>> (1,)
(1,)
>>> (,)
...
Traceback (  File "", line 1
(,)
 ^
SyntaxError: invalid syntax


-- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Injecting code into a function

2005-04-25 Thread Paddy
Try searching for: 'python aspect-oriented' as aspect oriented
programming is about modifying existing class-methods (not exactly
functions which is what you asked for).
You might also do a search for "AOP considered harmful"
http://www.infosun.fmi.uni-passau.de/st/papers/EIWAS04/stoerzer04aop_harmful.pdf

The main point is that when you are reading the source you don't know
what the code is as it may be augmented by an "external" change.

-- 
http://mail.python.org/mailman/listinfo/python-list


"Natural" use of cmp= in sort

2014-11-10 Thread Paddy
Hi, I do agree with 
 Raymond H. about the relative merits of cmp= and key= in 
sort/sorted, but I decided to also not let natural uses of cmp= pass silently.

In answering this question, http://stackoverflow.com/a/26850434/10562 about 
ordering subject to inequalities it seemed natural to use the cmp= argument of 
sort rather than key=.

The question is about merging given inequalities to make 1 inequality such that 
the inequalities also stays true.


Here is a copy of my code:

Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on 
win32
Type "copyright", "credits" or "license()" for more information.
>>> ineq = """f4 > f2 > f3
f4 > f1 > f3
f4 > f2 > f1
f2 > f1 > f3"""
>>> print(ineq)
f4 > f2 > f3
f4 > f1 > f3
f4 > f2 > f1
f2 > f1 > f3
>>> greater_thans, all_f = set(), set()
>>> for line in ineq.split('\n'):
tokens = line.strip().split()[::2]
for n, t1 in enumerate(tokens[:-1]):
for t2 in tokens[n+1:]:
greater_thans.add((t1, t2))
all_f.add(t1)
all_f.add(t2)


>>> sorted(all_f, cmp=lambda t1, t2: 0 if t1==t2 else 
...(1 if (t1, t2) not in greater_thans else -1))
['f4', 'f2', 'f1', 'f3']
>>> 

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "Natural" use of cmp= in sort

2014-11-10 Thread Paddy
On Monday, 10 November 2014 19:44:39 UTC, Ian  wrote:
> On Mon, Nov 10, 2014 at 12:19 PM, Peter Otten  wrote:
> > I'm not sure this works. I tried:
> 
> Here's a simpler failure case.
> 
> >>> ineq = """f2 > f3
> ... f3 > f1"""
> 
> [Previously posted code elided]
> 
> >>> greater_thans
> set([('f3', 'f1'), ('f2', 'f3')])
> >>> sorted(all_f, cmp=lambda t1, t2: 0 if t1==t2 else
> ... (1 if (t1, t2) not in greater_thans else -1))
> ['f1', 'f2', 'f3']
> 
> Note that the greater_thans set is missing the implication by
> transitivity that f2 > f1, so the given cmp function would
> inconsistently return -1 for both comparisons cmp('f1', 'f2') and
> cmp('f2', 'f1').

Thanks. I will look into this...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "Natural" use of cmp= in sort

2014-11-10 Thread Paddy
On Monday, 10 November 2014 18:45:15 UTC, Paddy  wrote:
> Hi, I do agree with   
>Raymond H. about the relative merits of cmp= and key= in 
> sort/sorted, but I decided to also not let natural uses of cmp= pass silently.
> 
> In answering this question, http://stackoverflow.com/a/26850434/10562 about 
> ordering subject to inequalities it seemed natural to use the cmp= argument 
> of sort rather than key=.
> 
> The question is about merging given inequalities to make 1 inequality such 
> that the inequalities also stays true.
> 
> 

Thanks Peter, Ian. I have modified my code to expand transitive relations and 
ask you to view it on stackoverflow via the original link (as posting code on 
newsgroups is an ugly hack).

My main reason for the post to c.l.p remains though; it seems like a *natural* 
use of the cmp= comparator function to sorted rather than using key= .

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "Natural" use of cmp= in sort

2014-11-10 Thread Paddy
On Tuesday, 11 November 2014 06:37:18 UTC, Ian  wrote:
> On Mon, Nov 10, 2014 at 8:09 PM, Paddy  wrote:
> > On Monday, 10 November 2014 18:45:15 UTC, Paddy  wrote:
> >> Hi, I do agree with
> >>   Raymond H. about the relative merits of cmp= and key= in 
> >> sort/sorted, but I decided to also not let natural uses of cmp= pass 
> >> silently.
> >>
> >> In answering this question, http://stackoverflow.com/a/26850434/10562 
> >> about ordering subject to inequalities it seemed natural to use the cmp= 
> >> argument of sort rather than key=.
> >>
> >> The question is about merging given inequalities to make 1 inequality such 
> >> that the inequalities also stays true.
> >>
> >>
> >
> > Thanks Peter, Ian. I have modified my code to expand transitive relations 
> > and ask you to view it on stackoverflow via the original link (as posting 
> > code on newsgroups is an ugly hack).
> 
> You still run into trouble though if the given inequalities don't
> provide enough information for a total ordering. E.g.:
> 
> >>> ' > '.join(extract_relations("""f4 > f1
> ... f2 > f3"""))
> 'f1 > f2 > f3 > f4'
> 
> By adding some debugging prints, we can see what cmp calls were made
> by the sort routine and what the results were:
> 
> cmp('f2', 'f1') -> 1
> cmp('f3', 'f2') -> 1
> cmp('f4', 'f3') -> 1
> 
> There is no information about the relative order of f2 and f1, so the
> cmp function just returns 1 there.
> f2 is known to be greater than f3, so that call correctly returns 1.
> There is again no information about the relative order of f4 and f3,
> so it again just returns 1. However, this is inconsistent with the
> first comparison that placed f1 > f2, because it implies that f1 > f4.
> 
> As you can see, giving an inconsistent cmp function to sort produces
> bogus results. If you only have a partial ordering of the inputs, you
> need to make sure that the cmp function you provide is consistent with
> *some* total ordering.
> 
> Another issue is that your expand_transitive_relations function is I
> think O(n**3 log n), which looks unattractive compared to the O(n**2)
> topological sort given in the other answers. Another advantage of the
> topological sort is that it will detect if the graph is cyclic (i.e.
> the input data itself is inconsistent), rather than just return a
> bogus output.
> 
> > My main reason for the post to c.l.p remains though; it seems like a 
> > *natural* use of the cmp= comparator function to sorted rather than using 
> > key= .
> 
> There are cases where a cmp function is more natural than a key
> function, but for these we have the functools.cmp_to_key adapter.

Thanks Ian. The original author states "...and it is sure that the given inputs 
will give an output, i.e., the inputs will always be valid.", which could be 
taken as meaning that all inputs are sufficient, well formed, and contain all 
relations as their first example does.

In that case, expand_transitive_relations is not even needed. Lets say it isn't 
for the sake of argument, then we are left with the direct use of cmp= versus a 
conversion to a key= function.

It seems to me that *in this case* the cmp= function naturally flows from the 
solution algorithm and that cmp_to_key is less so.

Yes, I knew that there are cases where a cmp function is more natural than key; 
the idea is to squirrel out a few. We have already made the, (well reasoned in 
my opinion), decision to go down the key= route in Python 3. I also like to 
track where my algorithms might originally map to cmp=. (It is not often).

My only other case of this type is here: 
http://stackoverflow.com/questions/15797120/can-this-cmp-function-be-better-written-as-a-key-for-sorted.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "Natural" use of cmp= in sort

2014-11-11 Thread Paddy
On Tuesday, 11 November 2014 09:07:14 UTC, Ian  wrote:
> On Tue, Nov 11, 2014 at 12:44 AM, Paddy  wrote:
> > Thanks Ian. The original author states "...and it is sure that the given 
> > inputs will give an output, i.e., the inputs will always be valid.", which 
> > could be taken as meaning that all inputs are sufficient, well formed, and 
> > contain all relations as their first example does.
> 
> Well, I brought it up because the start of that sentence is "There can
> be multiple inequalities as answer but I need any one which is
> correct...". The only way there would be more than one correct answer
> would be if the inputs were only partially ordered. I take the second
> part of the sentence as meaning only that the input can be safely
> assumed to be consistent.
> 
> > Yes, I knew that there are cases where a cmp function is more natural than 
> > key; the idea is to squirrel out a few. We have already made the, (well 
> > reasoned in my opinion), decision to go down the key= route in Python 3. I 
> > also like to track where my algorithms might originally map to cmp=. (It is 
> > not often).
> 
> Basically any time you have a comparison that isn't easily expressed
> by mapping the values to some bunch of ordered objects. 

Yep. I want to track when this comes up for me and others during their normal 
programming rather than in examples made to highlight the issue.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "Natural" use of cmp= in sort

2014-11-12 Thread Paddy
On Tuesday, 11 November 2014 18:07:27 UTC, Ian  wrote:
> The example that I posted is one that I recall being brought up on
> this list in the past, but I don't have a link for you.

THanks Ian for your help in this.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Bug in timsort!?

2015-02-25 Thread Paddy
On Wednesday, 25 February 2015 00:08:32 UTC, Chris Angelico  wrote:
> On Wed, Feb 25, 2015 at 10:50 AM, Skip Montanaro
>  wrote:
> > Even if/when we get to the point where machines can hold an array of
> > 2**49 elements, I suspect people won't be using straight Python to
> > wrangle them.
> 
<>
> 
> Would it be sufficient to stick a comment into the source saying "This
> may have problems with lists in excess of 2**49 elements", and leave
> it until that's actually likely to happen?
> 
> ChrisA

If we are given a proven fix with little downside then if we are to touch the 
source then we should MAKE THE FIX. To do otherwise would send the wrong signal 
to those that depend on the perceived integrity of the C-Python developers.
-- 
https://mail.python.org/mailman/listinfo/python-list


Need opinions on P vs NP

2015-04-17 Thread Paddy
Having just seen Raymond's talk on Beyond PEP-8 here: 
https://www.youtube.com/watch?v=wf-BqAjZb8M, it reminded me of my own recent 
post where I am soliciting opinions from non-newbies on the relative 
Pythonicity of different versions of a routine that has non-simple array 
manipulations.

The blog post: 
http://paddy3118.blogspot.co.uk/2015/04/pythonic-matrix-manipulation.html

The first, (and original), code sample:

def cholesky(A):
L = [[0.0] * len(A) for _ in range(len(A))]
for i in range(len(A)):
for j in range(i+1):
s = sum(L[i][k] * L[j][k] for k in range(j))
L[i][j] = sqrt(A[i][i] - s) if (i == j) else \
  (1.0 / L[j][j] * (A[i][j] - s))
return L


The second equivalent code sample:

def cholesky2(A):
L = [[0.0] * len(A) for _ in range(len(A))]
for i, (Ai, Li) in enumerate(zip(A, L)):
for j, Lj in enumerate(L[:i+1]):
s = sum(Li[k] * Lj[k] for k in range(j))
Li[j] = sqrt(Ai[i] - s) if (i == j) else \
  (1.0 / Lj[j] * (Ai[j] - s))
return L


The third:

def cholesky3(A):
L = [[0.0] * len(A) for _ in range(len(A))]
for i, (Ai, Li) in enumerate(zip(A, L)):
for j, Lj in enumerate(L[:i]):
#s = fsum(Li[k] * Lj[k] for k in range(j))
s = fsum(Lik * Ljk for Lik, Ljk in zip(Li, Lj[:j]))
Li[j] = (1.0 / Lj[j] * (Ai[j] - s))
s = fsum(Lik * Lik for Lik in Li[:i])
Li[i] = sqrt(Ai[i] - s)
return L

My blog post gives a little more explanation, but I have yet to receive any 
comments on relative Pythonicity.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need opinions on P vs NP

2015-04-17 Thread Paddy
On Saturday, 18 April 2015 03:34:57 UTC+1, Ian  wrote:
> On Fri, Apr 17, 2015 at 7:19 PM, Paddy  wrote:
> > Having just seen Raymond's talk on Beyond PEP-8 here: 
> > https://www.youtube.com/watch?v=wf-BqAjZb8M, it reminded me of my own 
> > recent post where I am soliciting opinions from non-newbies on the relative 
> > Pythonicity of different versions of a routine that has non-simple array 
> > manipulations.
> >
> > The blog post: 
> > http://paddy3118.blogspot.co.uk/2015/04/pythonic-matrix-manipulation.html
> >
> > The first, (and original), code sample:
> >
> > def cholesky(A):
> > L = [[0.0] * len(A) for _ in range(len(A))]
> > for i in range(len(A)):
> > for j in range(i+1):
> > s = sum(L[i][k] * L[j][k] for k in range(j))
> > L[i][j] = sqrt(A[i][i] - s) if (i == j) else \
> >   (1.0 / L[j][j] * (A[i][j] - s))
> > return L
> >
> >
> > The second equivalent code sample:
> >
> > def cholesky2(A):
> > L = [[0.0] * len(A) for _ in range(len(A))]
> > for i, (Ai, Li) in enumerate(zip(A, L)):
> > for j, Lj in enumerate(L[:i+1]):
> > s = sum(Li[k] * Lj[k] for k in range(j))
> > Li[j] = sqrt(Ai[i] - s) if (i == j) else \
> >   (1.0 / Lj[j] * (Ai[j] - s))
> > return L
> >
> >
> > The third:
> >
> > def cholesky3(A):
> > L = [[0.0] * len(A) for _ in range(len(A))]
> > for i, (Ai, Li) in enumerate(zip(A, L)):
> > for j, Lj in enumerate(L[:i]):
> > #s = fsum(Li[k] * Lj[k] for k in range(j))
> > s = fsum(Lik * Ljk for Lik, Ljk in zip(Li, Lj[:j]))
> > Li[j] = (1.0 / Lj[j] * (Ai[j] - s))
> > s = fsum(Lik * Lik for Lik in Li[:i])
> > Li[i] = sqrt(Ai[i] - s)
> > return L
> >
> > My blog post gives a little more explanation, but I have yet to receive any 
> > comments on relative Pythonicity.
> 
> I prefer the first version. You're dealing with mathematical formulas
> involving matrices here, so subscripting seems appropriate, and
> enumerating out rows and columns just feels weird to me.
> 
> That said, I also prefer how the third version pulls the last column
> of each row out of the inner loop instead of using a verbose
> conditional expression that you already know will be false for every
> column except the last one. Do that in the first version, and I think
> you've got it.

But shouldn't the maths transcend the slight change in representation? A 
programmer in the J language might have a conceptually neater representation of 
the same thing due to its grounding in arrays (maybe) and for a J 
representation it would become J-thonic. In Python, it is usual to iterate over 
collections and also to use enumerate where we must have indices. 

Could it be that there is a also a strong pull in the direction of using 
indices because that is what is predominantly given in the way matrix maths is 
likely to be expressed mathematically? A case of "TeX likes indices so we 
should too"?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need opinions on P vs NP

2015-04-18 Thread Paddy
On Saturday, 18 April 2015 08:09:06 UTC+1, [email protected]  wrote:
> Le samedi 18 avril 2015 03:19:40 UTC+2, Paddy a écrit :
> > Having just seen Raymond's talk on Beyond PEP-8 here: 
> > https://www.youtube.com/watch?v=wf-BqAjZb8M, it reminded me of my own 
> > recent post where I am soliciting opinions from non-newbies on the relative 
> > Pythonicity of different versions of a routine that has non-simple array 
> > manipulations.
> > 
> > The blog post: 
> > http://paddy3118.blogspot.co.uk/2015/04/pythonic-matrix-manipulation.html
> > 
> > The first, (and original), code sample:
> > 
> > def cholesky(A):
> > L = [[0.0] * len(A) for _ in range(len(A))]
> > for i in range(len(A)):
> > for j in range(i+1):
> > s = sum(L[i][k] * L[j][k] for k in range(j))
> > L[i][j] = sqrt(A[i][i] - s) if (i == j) else \
> >   (1.0 / L[j][j] * (A[i][j] - s))
> > return L
> > 
> > 
> > The second equivalent code sample:
> > 
> > def cholesky2(A):
> > L = [[0.0] * len(A) for _ in range(len(A))]
> > for i, (Ai, Li) in enumerate(zip(A, L)):
> > for j, Lj in enumerate(L[:i+1]):
> > s = sum(Li[k] * Lj[k] for k in range(j))
> > Li[j] = sqrt(Ai[i] - s) if (i == j) else \
> >   (1.0 / Lj[j] * (Ai[j] - s))
> > return L
> > 
> > 
> > The third:
> > 
> > def cholesky3(A):
> > L = [[0.0] * len(A) for _ in range(len(A))]
> > for i, (Ai, Li) in enumerate(zip(A, L)):
> > for j, Lj in enumerate(L[:i]):
> > #s = fsum(Li[k] * Lj[k] for k in range(j))
> > s = fsum(Lik * Ljk for Lik, Ljk in zip(Li, Lj[:j]))
> > Li[j] = (1.0 / Lj[j] * (Ai[j] - s))
> > s = fsum(Lik * Lik for Lik in Li[:i])
> > Li[i] = sqrt(Ai[i] - s)
> > return L
> > 
> > My blog post gives a little more explanation, but I have yet to receive any 
> > comments on relative Pythonicity.
> 
> 
> 
> def cholesky999(A):
> n = len(A)
> L = [[0.0] * n for i in range(n)]
> for i in range(n):
> for j in range(i+1):
> s = 0.0
> for k in range(j):
> s += L[i][k] * L[j][k]
> if i == j:
> L[i][j] = sqrt(A[i][i] - s)
> else:
> L[i][j] = (1.0 / L[j][j] * (A[i][j] - s))
> return L
> 
> Simple, clear, logical, consistant.

And so most Pythonic? Maybe so.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Online Ruby

2005-12-14 Thread Paddy
That reminds me of TclTutor:
  http://www.msen.com/~clif/TclTutorTour.html

TclTutor is a great Tk application that teaches Tcl/Tk by having all
the lessons and examples set up waiting in the app. The examples can be
edited/fixed and re-executed.

I still bring up TclTutor when I delve into Tcl programming (after
several years), it is invaluable.

I guess a Python equivalent would be Idle, pre-packaged with lessons
and examples from the Python tutorial available from the Idle menus.

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python coding contest

2005-12-31 Thread Paddy
So, testosterone wins again!

We get to boast:
  "Mine's smaller than your's"

Lets wait for Pythonic to go to bed, then sneak downstairs, go to that
tripple-X rated 'shortest solutions' website, and 'whack-off' some
solutions.
Unghhh,  my solution... its coming!!!

Well don't forget to clean up before Pythonic wakes up.

Happy new year :-)

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehention

2006-01-19 Thread Paddy
Hi,
I liked the twist at the end when you state that only the first two 2's
count. It reminded me
of my maths O'level revision where you always had to read the question
thoroughly.

Here is what I came up with:

>>> ref
[2, 2, 4, 1, 1]
>>> lst
[2, 2, 5, 2, 4]
>>> tmp = [ [val]*min(lst.count(val), ref.count(val)) for val in set(ref)]
>>> tmp
[[], [2, 2], [4]]
>>> answer = [x for y in tmp for x in y]
>>> answer
[2, 2, 4]
>>>

I took a lot from Peter Ottens reply to generate tmp then flattened the
inner lists.

After a bit more thought, the intermediate calculation of tmp can be
removed with a
little loss in clarity though, to give:

>>> answer = [ val for val in set(ref) for x in range(min(lst.count(val), 
>>> ref.count(val)))]
>>> answer
[2, 2, 4]



- Cheers,  Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: instances

2006-07-14 Thread Paddy
Quenton Bonds wrote:
> Hello
> I am trying to understand the abilities and limitation of creating an
> instance.  First I will give you my understanding then please steer me
> in the right direction.
>
> Abiities
> 1.  The two ways to create an instance is def method(self) &
> __int__(self, other, instances,...)
> 2.  By creating an instance of a method; the functions of that method
> can be used through out the
>program in a fashion such as self.methodofprogram(parameters)
> Limitations
> 3.  One cannot create an instance of a class.
> 4.  An instance can only perform functions that are provided from the
> method it was instanced from.
>
> 5.  Is there any other key information I am missing.
Hi Quentin,
Might you be new to programming, or new to Object Oriented programming?
You might profit from reading some of the beginners tutorials mentioned
here:
  http://wiki.python.org/moin/BeginnersGuide
which points to
  http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

Here is some info to correct your statements above (but it is not a
tutorial)!

The class statement creates a 'class definition'.
E.g:
  class my_class():
pass
Instances of a class are created by using the class name followed by
parenthesis,
E.g:
  my_inst = my_class()

If a class has methods:
  class my_class2:
def my_method(self):
  pass
Then an instance of the class:
  my_inst2 = my_class2()
Can access its method like this:
  my_inst2.my_method()

Trying to access a method of the class that does not exist will produce
an error.
E.g:
  my_inst2.missing_method()
Will give an error, (throw an exception in Python terminology)..

The above is just a (poor) taste. Dive into one of the beginners
tutorials.

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using names before they're defined

2006-07-19 Thread Paddy

[EMAIL PROTECTED] wrote:
> I have a problem. I'm writing a simulation program with a number of
> mechanical components represented as objects. When I create instances
> of objects, I need to reference (link) each object to the objects
> upstream and downstream of it, i.e.
>
> supply = supply()
> compressor = compressor(downstream=combustor, upstream=supply)
> combuster = combuster(downstream=turbine, upstream=compressor)
> etc.
>
> the problem with this is that I reference 'combustor' before is it
> created. If I swap the 2nd and 3rd lines I get the same problem
> (compressor is referenced before creation).
>
>
> aargh!!! any ideas on getting around this?
>
> Dave
Hi Dave,
In Digital electronics we have what are called netlists, (and also
component lists)

We have component types (map them to component objects); named
instances of components (instances); then we have net types (you could
probably get away with one net type) which models connections between
ports on a component.


class Port:
  def __init__(self, direction):
  self.direction = direction
class Comp:
  def __init__(self,compType,name):
  self.upstream = Port("U")
  self.downstream = Port("D")
  self.name = name
  self.compType = compType
class Link:
def __init__(self, name, *connections):
self.connections = connections
self.name = name

# Instantiate your components
supply1 = Comp("supply", "supply1")
supply2 = Comp("supply", "supply2")
compressor1 = Comp("compressor", "compressor1")

# Instantiate Links and link in ports of component intances
supply2comp = Link("supply2comp", supply1.downstream,
compressor1.upstream)
# ...

With a bit more effort you can create component and link factories
that will name instances with the variable they are assigned to
without having to put that information in twice.

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language Design: list_for scope?

2006-07-21 Thread Paddy

guthrie wrote:
> I'm pretty new to Python, and trying to parse the grammar.
>
> Q: What is the scope of the testlist in a list_for?
>
> For example;
> Instead of;
>   for x in [ x in dict if dict[x]=="thing" ]:
> in this:
>   for x in dict and dict[x]=="thing":
> x is undefined.
>
> And why doesn't this work:
>   for x in dict if dict[x]=="thing":
>
> Any insights/hints on why it is broken?
>
> Thanks,
> Gregory
> 
> http://docs.python.org/ref/grammar.txt:
> list_for ::=
>   "for" expression_list "in" testlist
>[list_iter]
> testlist ::=
>   test ( "," test )* [ "," ]
> list_iter ::=
>   list_for | list_if
> list_if ::=
>   "if" test [list_iter]
>
>
> == Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
> News==
> http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
> Newsgroups
> = East and West-Coast Server Farms - Total Privacy via Encryption =

It is hard to answer your "Why doesn't this wirk question|", and it
must be hard to approach Python as a new user by looking at the
grammer.
Why not try looking at examples, trying them out in the Idle IDE, and
only then compare  your working examples to the grammer?

Here is a page with examples you could type in or vary in the
interpreter:

http://nltk.sourceforge.net/tutorial/advpython/nochunks.html#list_comprehensions

Cheers, Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type signature

2006-07-23 Thread Paddy
Yacao Wang wrote:
> Hi, I'm a newbie to Python. I've recently read some books about this
> language and none of them have answered my question.
> As a dynamically-typed language Python doesn't need any form of type
> signature which makes the syntax very clean and concise. However, type
> signatures are not only a kind of information provided for the compiler, but
> also for the programmer, or more important, for the programmer. Without it,
> we have to "infer" the return type or required agument types of a function,
> and this can't be done without seeing the implementation of it, and
> sometimes it is still difficult to extract the above information even if the
> implementation is available. Haskell can also determine type information
> dynamically, but it still supports and recommends the programming style with
> type signatures, which makes the code very readable and maitainable. As I
> understand, Python relies too much on run-time type-checking, that is,
> whenever you give the wrong type, you just end up with an exception, which
> is logically correct, but not that useful as type signatures.
> Any ideas on this issue?
>
> --
> Alex
>
Hi Yacao/Alex,
Try these:
  "How to duck type? - the psychology of static typing in Ruby"
   http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/100511
  "3-31-04 I'm Over It"

http://66.102.9.104/search?q=cache:6XW473VSflcJ:www.mindview.net/WebLog/log-0053+%2B%22duck+typing%22+%2B+%22static+typing%22+%2Bpython&hl=en&gl=uk&ct=clnk&cd=3&client=firefox-a

It seems that the latent or duck typing, used in dynamic languages is
counter-intuitve to  those from a static typing background.
Nevertheless, it does work, and work well.
- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a compelling argument to use Django instead of Rails

2006-07-24 Thread Paddy

Ray wrote:
> I just moved to another company that's mainly a Java/.NET shop. I was
> happy to find out that there's a movement from the grassroot to try to
> convince the boss to use a dynamic language for our development!
>
> Two of the senior developers, however, are already rooting for Ruby on
> Rails--although they haven't tried RoR themselves. When I suggested
> Django, they went like, "what's that?".
>
> I said, "It's like the Python counterpart of RoR".
>
> "Nah, we're not interested in Python."
>
> I think they are already predisposed to RoR simply because of RoR's
> visibility (i.e.: at my workplace everybody knows RoR but nobody knows
> about Django unless they've used Python as well). So far the arguments
> I can think of:
>
> 1. The investment of learning Python will be a good investment because
> it transfer to platforms that we've already supported, i.e.: JVM and
> .NET CLR (using Jython and IronPython). Ruby's availability on this
> platform is not as mature--JRuby is still at 0.9 and I don't think
> IronRuby is coming out anytime soon :)
>
> 2. Python is a much more mature language than Ruby--it's been around
> since ages ago and as such has a lot more tools, articles, and other
> resources than Ruby. It is also the language being used by
> high-visibility company like Google, with the creator of the language
> himself working there.
>
> 3. Python emphasizes readability instead of cleverness/conciseness.
>
> 4. What else? I haven't tried RoR so I can't argue meaningfully on
> whether using Django will put us at an advantage.
>
> Can you help me with my argument? Meanwhile I think I'll give RoR a try
> as well.
> 
> Thank you,
> Ray

Ruby does not have doctest :-)

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads vs Processes

2006-07-26 Thread Paddy

Carl J. Van Arsdall wrote:
> Alright, based a on discussion on this mailing list, I've started to
> wonder, why use threads vs processes.  So, If I have a system that has a
> large area of shared memory, which would be better?  I've been leaning
> towards threads, I'm going to say why.
>
> Processes seem fairly expensive from my research so far.  Each fork
> copies the entire contents of memory into the new process.  There's also
> a more expensive context switch between processes.  So if I have a
> system that would fork 50+ child processes my memory usage would be huge
> and I burn more cycles that I don't have to.  I understand that there
> are ways of IPC, but aren't these also more expensive?
>
> So threads seems faster and more efficient for this scenario.  That
> alone makes me want to stay with threads, but I get the feeling from
> people on this list that processes are better and that threads are over
> used.  I don't understand why, so can anyone shed any light on this?
>
>
> Thanks,
>
> -carl
>
> --
>
> Carl J. Van Arsdall
> [EMAIL PROTECTED]
> Build and Release
> MontaVista Software

Carl,
 OS writers provide much more tools for debugging, tracing, changing
the priority of, sand-boxing processes than threads (in general) It
*should* be easier to get a process based solution up and running
andhave it be more robust, when compared to a threaded solution.

- Paddy (who shies away from threads in C and C++ too ;-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using iterators to write in the structure being iterated through?

2006-07-26 Thread Paddy

Pierre Thibault wrote:
> Hello!
>
> I am currently trying to port a C++ code to python, and I think I am stuck
> because of the very different behavior of STL iterators vs python
> iterators. What I need to do is a simple arithmetic operations on objects
> I don't know. In C++, the method doing that was a template, and all that
> was required is that the template class has an iterator conforming to the
> STL forward iterator definition. Then, the class would look like:
>

> Then I discovered python and wanted to use all its goodies. I thought it
> would be easy to do the same thing but I can't: the iterator mechanism is
> read-only, right? So it does no make sense to write:
>
> io1 = iter(object1)
> io2 = iter(object2)
>
> try:
>   while 1:
> io1.next() += io2.next()
> except StopIteration:
>   pass
>
> That won't work:
> SyntaxError: can't assign to function call
>
> Here is my question: how could I do that and retain enough generallity?
>
> Thanks!
>
> Pierre

Pierre,
You should be able to write
  io1.next().param += io2.next().param
If iter(object1) and iter(object2) both return classes or instances
with the appropriate parameter.
Here is what I was thinking of:


class ParamHolder(object):
def __init__(self, n):
self.param = n

class C1(object):
def __init__(self,m):
self.value = [ParamHolder(n) for n in range(m)]
def __getitem__(self, p):
return self.value[p]

obj1 = C1(5)
obj2 = C1(5)

io1 = iter(obj1)
io2 = iter(obj2)

print "obj1 pre loop",[r.param for r in obj1.value]

try:
while 1:
io1.next().param += io2.next().param
except StopIteration:
pass

print "obj1 post loop",[r.param for r in obj1.value]

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using iterators to write in the structure being iterated through?

2006-07-26 Thread Paddy

Paddy wrote:
> Pierre Thibault wrote:
> > Hello!
> >
> > I am currently trying to port a C++ code to python, and I think I am stuck
> > because of the very different behavior of STL iterators vs python
> > iterators. What I need to do is a simple arithmetic operations on objects
> > I don't know. In C++, the method doing that was a template, and all that
> > was required is that the template class has an iterator conforming to the
> > STL forward iterator definition. Then, the class would look like:
> >
> 
> > Then I discovered python and wanted to use all its goodies. I thought it
> > would be easy to do the same thing but I can't: the iterator mechanism is
> > read-only, right? So it does no make sense to write:
> >
> > io1 = iter(object1)
> > io2 = iter(object2)
> >
> > try:
> >   while 1:
> > io1.next() += io2.next()
> > except StopIteration:
> >   pass
> >
> > That won't work:
> > SyntaxError: can't assign to function call
> >
> > Here is my question: how could I do that and retain enough generallity?
> >
> > Thanks!
> >
> > Pierre
>
> Pierre,
> You should be able to write
>   io1.next().param += io2.next().param
> If iter(object1) and iter(object2) both return classes or instances
> with the appropriate parameter.
> Here is what I was thinking of:
>
>
> class ParamHolder(object):
> def __init__(self, n):
> self.param = n
>
> class C1(object):
> def __init__(self,m):
> self.value = [ParamHolder(n) for n in range(m)]
> def __getitem__(self, p):
> return self.value[p]
>
> obj1 = C1(5)
> obj2 = C1(5)
>
> io1 = iter(obj1)
> io2 = iter(obj2)
>
> print "obj1 pre loop",[r.param for r in obj1.value]
>
> try:
> while 1:
> io1.next().param += io2.next().param
> except StopIteration:
> pass
>
> print "obj1 post loop",[r.param for r in obj1.value]
>
> - Paddy.

I don't like the try/except code and would write something like the
following:

>>> obj1 = C1(5)
>>> obj2 = C1(5)
>>> from itertools import izip
>>> for x,y in izip(obj1, obj2):
... x.param += y.param
...
>>> print "obj1 post for loop",[r.param for r in obj1.value]
obj1 post for loop [0, 2, 4, 6, 8]
>>> 

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scope, type and UnboundLocalError

2006-07-26 Thread Paddy

Paddy wrote:
> Hi,
> I am trying to work out why I get UnboundLocalError when accessing an
> int from a function where the int is at the global scope, without
> explicitly declaring it as global but not when accessing a list in
> similar circumstances.
>
> The documentation: http://docs.python.org/ref/naming.html does not give
> me enough info to determine why the difference exists as it does not
> seem to mention types at all..
>
> The code:
>
> = scope_and_type.py ===
> m = 0
> n = [0]
>
> def int_access0():
> m = m + 1
> return m
> def int_access1():
> m += 1
> return m
> def list_access0():
> n[0] = n[0] + 1
> return n
> def list_access1():
> n[0] += 1
> return n
>
> try:
> print "\nint_access0:", int_access0()
> except UnboundLocalError, inst:
> print " ERROR:\n", inst
> try:
> print "\nint_access1:", int_access1()
> except UnboundLocalError, inst:
> print " ERROR:\n", inst
> try:
> print "\nlist_access0:", list_access0()
> except UnboundLocalError, inst:
> print " ERROR:\n", inst
> try:
> print "\nlist_access1:", list_access1()
> except UnboundLocalError, inst:
> print " ERROR:\n", inst
>
>
> print "\n (m,n) = ", (m,n)
>
>
> p = (0,)
> def tuple_access():
> return p[0]
> try:
> print "\ntuple_acces:", tuple_access()
> except UnboundLocalError, inst:
> print " ERROR:\n", inst
> print "\n p = ", p
>
> = END scope_and_type.py ===
>
> The output:
> >>>
> int_access0:  ERROR:
> local variable 'm' referenced before assignment
>
> int_access1:  ERROR:
> local variable 'm' referenced before assignment
>
> list_access0: [1]
>
> list_access1: [2]
>
>  (m,n) =  (0, [2])
>
> tuple_acces: 0
>
>  p =  (0,)
> >>>

I blogged the following as a summary:
(From:
http://paddy3118.blogspot.com/2006/07/python-functions-assignments-and-scope.html)

 Python Functions: Assignments And Scope

Explaining why this works:

n = [0]
def list_access():
   n[0] = n[0] + 1
   return n

try:
   print "\nlist_access:", list_access()
except UnboundLocalError, inst:
   print " ERROR:\n", inst

And this throws the exception:

m = 0
def int_access():
   m = m + 1
   return m

try:
   print "\nint_access:", int_access()
except UnboundLocalError, inst:
   print " ERROR:\n", inst

To execute a source program, the Python compiler compiles your
original source into 'byte codes' - a form of your program that
is easier for the Python interpreter to later run. In generating this
byte code, the byte code compiler will determine which variable names
in a function are local to that function, (so alowing it to optimise
accesses to such local names).

The rule for determining if a variable is local to a function is:

* If there is a global statement for the name in the function
  then the name is accessed from the global scope.
* If there is no global statement for the name, and if there
  are assignments to the 'bare' name within the function then the
name
  is of local scope.
  ( A bare name assignment means assignment to a
  name, where the name occurs without attribute references,
  subscripts, or slicing s, just the bare name).
* Otherwise the name will be looked up in reverse order of all
  enclosing scopes, until it is found.

In the second example, function int_access; name m is flagged as
local by the byte code compiler as the bare name is being assigned
to. The interpreter therefore looks for a value of m to increment
only in the local scope, cannot find a value, then raises the
UnboundLocalError exception.
In function list_access, the bare
name n is not assigned to, so n is found when looking back
through enclosing scopes.
References

   1.


http://groups.google.com/group/comp.lang.python/browse_frm/thread/db9955da70c4e0ca
   2.

  http://pyref.infogami.com/assignments
   3.

  http://pyref.infogami.com/naming-and-binding
   4.

  http://www.python.org/doc/2.4/ref/global.html

END.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: metaclass : parse all class once before doing anything else ?

2006-07-29 Thread Paddy

Laurent Rahuel wrote:
> Hi,
>
> I have a much to smart problem for my brain.
>
> Here is the deal :
>
> I got a metaclass named Foo
>
> Then I got two others classes:
>
> class Bar(Foo):
> pass
>
> class Baz(Foo):
> pass
>
> I know how to add some attrs, methods to Bar and Baz when the module is
> loaded but I need to do something more :
>
> Before adding anything to these classes,
> 1 - I need to parse all defined Foo classes
> 2 - "sort" them
> 3 - parse this sorted list to add attrs and methods.
>
> This seems to be really to clever for me ;-(
>
> Any idea ?
>
> Regards,
>
> Laurent.

I, like Diez am unsure of why you would need what you have asked for,
but maybe this will help.

You can keep  track of all instances of a class by this kind of thing:

>>> class C1(object):
... inst = []
... def __init__(self):
... self.inst.append(self)
...
>>> i1 = C1()
>>> i2 = C1()
>>> print i1,i2
<__main__.C1 object at 0x0128C970> <__main__.C1 object at 0x0128CA50>
>>> print C1.inst
[<__main__.C1 object at 0x0128C970>, <__main__.C1 object at
0x0128CA50>]
>>>

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Static Variables in Python?

2006-07-31 Thread Paddy

Michael Yanowitz wrote:
> Is it possible to have a static variable in Python -
> a local variable in a function that retains its value.
>
>  For example, suppose I have:
>
> def set_bit (bit_index, bit_value):
>static bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>bits [bit_index] = bit_value
>
>print "\tBit Array:"
>int i
>while (i < len(bits):
>   print bits[i],
>print '\n'
>
>
>I realize this can be implemented by making bits global, but can
> this be done by making it private only internal to set_bit()?  I don't
> want bits to be reinitialized each time. It must retain the set values
> for the next time it is called.
>
>
> Thanks in advance:
> Michael Yanowitz

You can do things with function attributes

def foo(x):
  foo.static += x
  return foo.static
foo.static = 0

If you are going to set function attributes a lot, then you might like
to addd an attriute setter decorator to your toolbox:

def attributeSetter( **kw):
" decorator creator: initialises function attributes"
def func2(func):
" decorator: initialises function attributes"
func.__dict__.update(kw)
return func
return func2

def accumulator(n):
""" return an accumulator function that starts at n
>>> x3 = accumulator(3)
>>> x3.acc
3
>>> x3(4)
7
>>> x3.acc
7
"""
@attributeSetter(acc = n)
def accum(i):
accum.acc+= i
return accum.acc
return accum


- Paddy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Railroad track syntax diagrams

2006-08-01 Thread Paddy

Paul McGuire wrote:
> Back in the mid-90's, Kees Blom generated a set of railroad syntax diagrams
> for Python
> (http://python.project.cwi.nl/search/hypermail/python-1994q3/0286.html).
> This pre-dates any Python awareness on my part, but I'm sure this would have
> been version 1.3 or something.
>
> For those who are not familiar with railroad syntax diagrams, they show a
> grammar's syntax using arrows and blocks, instead of BNF - here's an excerpt
> from the Python grammar, plus "ASCII-art" diagrams - must be viewed in
> non-prop font to be appreciated:
>
> suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
>
> +--> simple_stmt ->\
> |   |
> \--> NEWLINE --> INDENT --+--> stmt --+--> DEDENT --+-->
>  /|
>  \<---/
>
> if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
>
>
> --> 'if' -> test --> ':' --> suite -->+
>   |
>   <---+
>  /
> +
> | <
> |/ \
> +  |
> |  |
> +-> 'elif' -> test -> ':' --> suite -->/
> |
> |
> +-> 'else' -> ':' --> suite -->
> |  \
> \>--+--->
>
>
> I was recently contacted by a volunteer in Banda Aceh teaching tsunami
> refugees how to program in Python (new job skills and all that), and he
> asked if there were any updated versions of these diagrams, or if it would
> be difficult to generate them anew.   It seems that railroad diagrams are
> nice and unambiguous for his students to use, in the face of verbal language
> barriers.
>
> I have written a pyparsing parser that reads the grammar file that ships
> with Python - the parser is included in the latest release of pyparsing, and
> also online at the pyparsing.wikispaces.com - but I have no graph-generating
> tools to go the next step: generation of the railroad diagrams (in something
> more legible/appealing than ASCII-art!).
>
> Anyone interested in helping complete this last step?
>
> Thanks,
> -- Paul
I googlled and got these:
  http://www.informatik.uni-freiburg.de/~thiemann/haskell/ebnf2ps/
  http://www.antlr.org/share/1107033888258/SDG2-1.5.zip

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Railroad track syntax diagrams

2006-08-01 Thread Paddy

Paddy wrote:
> Paul McGuire wrote:
> > Back in the mid-90's, Kees Blom generated a set of railroad syntax diagrams
> > for Python
> > (http://python.project.cwi.nl/search/hypermail/python-1994q3/0286.html).
> > This pre-dates any Python awareness on my part, but I'm sure this would have
> > been version 1.3 or something.
> >
> > For those who are not familiar with railroad syntax diagrams, they show a
> > grammar's syntax using arrows and blocks, instead of BNF - here's an excerpt
> > from the Python grammar, plus "ASCII-art" diagrams - must be viewed in
> > non-prop font to be appreciated:
> >
> > suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
> >
> > +--> simple_stmt ->\
> > |   |
> > \--> NEWLINE --> INDENT --+--> stmt --+--> DEDENT --+-->
> >  /|
> >  \<---/
> >
> > if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
> >
> >
> > --> 'if' -> test --> ':' --> suite -->+
> >   |
> >   <---+
> >  /
> > +
> > | <
> > |/ \
> > +  |
> > |  |
> > +-> 'elif' -> test -> ':' --> suite -->/
> > |
> > |
> > +-> 'else' -> ':' --> suite -->
> > |  \
> > \>--+--->
> >
> >
> > I was recently contacted by a volunteer in Banda Aceh teaching tsunami
> > refugees how to program in Python (new job skills and all that), and he
> > asked if there were any updated versions of these diagrams, or if it would
> > be difficult to generate them anew.   It seems that railroad diagrams are
> > nice and unambiguous for his students to use, in the face of verbal language
> > barriers.
> >
> > I have written a pyparsing parser that reads the grammar file that ships
> > with Python - the parser is included in the latest release of pyparsing, and
> > also online at the pyparsing.wikispaces.com - but I have no graph-generating
> > tools to go the next step: generation of the railroad diagrams (in something
> > more legible/appealing than ASCII-art!).
> >
> > Anyone interested in helping complete this last step?
> >
> > Thanks,
> > -- Paul
> I googlled and got these:
>   http://www.informatik.uni-freiburg.de/~thiemann/haskell/ebnf2ps/
>   http://www.antlr.org/share/1107033888258/SDG2-1.5.zip
>
> - Paddy.

And this suite includes a digram generator:

http://www.research.philips.com/technologies/syst_softw/elegant/index.html

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More int and float attributes

2006-08-05 Thread Paddy

[EMAIL PROTECTED] wrote:
> sys.maxint gives the largest positive integer supported by Python's
> regular integer type. But maybe such attribute, with few others (they
> can be called min and max) can be given to int type itself.
> D is a very nice language, that I hope to see more used. It is copying
> lot of things from Python. D Floating point values have some
> proprieties:
>
> http://www.digitalmars.com/d/property.html
>
> Properties for Floating Point Types:
> .init initializer (NaN)
> .infinity infinity value
> .nan  NaN value
> .dig  number of decimal digits of precision
> .epsilon  smallest increment
> .mant_dig number of bits in mantissa
> .max_10_exp   maximum exponent as power of 10
> .max_exp  maximum exponent as power of 2
> .min_10_exp   minimum exponent as power of 10
> .min_exp  minimum exponent as power of 2
> .max  largest representable value that's not infinity
> .min  smallest representable value that's not 0
> .re   real part
> .im   imaginary part
>
> I think such attributes may be useful to be added to Python float
> type/values too.
>
> Bye,
> bearophile
The thing about float is that people expect it to be 'fast'. Most CPU's
have two or one representationfor floats that is supported by hardware
and lightning fast compared to a pure software implementation.
The decimal module provides for the 'bean counters' out their who can't
afford to round off a penny, but I must say that this is the first
request I have seen for a flexible float where you would not have
hardware support (when hardware float support is available).

Or do you mean the ability to choose between hardware supported float
s? e.g. float and double precision?
Or to be able to just interrogate the float implementation so your prog
can adjust to whatever implementation it is running under?
Something like:
  assert float.mant_dig > 20


- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Something for PyPy developers?

2006-08-05 Thread Paddy
I just found this:
  http://www.cs.princeton.edu/~dpw/popl/06/Tim-POPL.ppt
And thought of you... :-)

called "The Next Mainstream Programming Languages", Tim Sweeney of Epic
Games presents on problems that game writers see and muses on possible
solutions.

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More int and float attributes

2006-08-05 Thread Paddy

[EMAIL PROTECTED] wrote:
> Paddy:
> > Or do you mean the ability to choose between hardware supported float
> > s? e.g. float and double precision?
>
> No, I mean just having the ability to ask the float (his attribute)
> what are the max and min values it can represent, etc.
>
> stop = float.max
> ...
>
> I don't know any simple way to know that values now. And importing sys
> to know the max int looks stupid.
>
> maxi = int.max
> mini = int.min
> ...
>
> Such attributes can be given to the Decimal values too, if you want.
>
> Bye,
> bearophile
Hi  bearophille,
decimals have their context; maybe floats could have your read-only
'context' values made available somehow. I don't know if their is an
issue with making this (static) data available from all float
instances, so maybe it should go in sys.

Maybe people, (me included), don't pay enough attention to the
trade-offs inherent in floating point arithmatic. I was taught about
difference equations, and rounding errors. I regularly compute answers
in programs without regard to floating point precision because the
defaults chosen work for most of my cases, but if I needed to be more
precise then I too would need some of the info you suggest.

Question: do the scientific packages supported by Python supply this
data in a regular manner?

- Paddy.

P.S. My appologies to any professional 'counters of currencies' out
their who may have been offended by my earlier use of the term 'bean
counters' - You probably earn much more than me - don't call in my
loans - I have babes in arms to feed  :-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More int and float attributes

2006-08-05 Thread Paddy

Paddy wrote:
> [EMAIL PROTECTED] wrote:
> > Paddy:
> > > Or do you mean the ability to choose between hardware supported float
> > > s? e.g. float and double precision?
> >
> > No, I mean just having the ability to ask the float (his attribute)
> > what are the max and min values it can represent, etc.
> >
> > stop = float.max
> > ...
> >
> > I don't know any simple way to know that values now. And importing sys
> > to know the max int looks stupid.
> >
> > maxi = int.max
> > mini = int.min
> > ...
> >
> > Such attributes can be given to the Decimal values too, if you want.
> >
> > Bye,
> > bearophile
> Hi  bearophille,
> decimals have their context; maybe floats could have your read-only
> 'context' values made available somehow. I don't know if their is an
> issue with making this (static) data available from all float
> instances, so maybe it should go in sys.
>
> Maybe people, (me included), don't pay enough attention to the
> trade-offs inherent in floating point arithmatic. I was taught about
> difference equations, and rounding errors. I regularly compute answers
> in programs without regard to floating point precision because the
> defaults chosen work for most of my cases, but if I needed to be more
> precise then I too would need some of the info you suggest.
>
> Question: do the scientific packages supported by Python supply this
> data in a regular manner?
>
> - Paddy.
>
> P.S. My appologies to any professional 'counters of currencies' out
> their who may have been offended by my earlier use of the term 'bean
> counters' - You probably earn much more than me - don't call in my
> loans - I have babes in arms to feed  :-)

P.P.S. Just looking at the values you propose, if some of them can be
computed reliably from others (in the given float precision), then they
should NOT be included, but the module documentation should state how
they can be derived.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Static Variables in Python?

2006-08-07 Thread Paddy

Cameron Laird wrote:
> In article <[EMAIL PROTECTED]>,
> Paddy <[EMAIL PROTECTED]> wrote:
>   .
>   [substantial thread
>   with many serious
>   alternatives]
>   .
>   .
> >You can do things with function attributes
> >
> >def foo(x):
> >  foo.static += x
> >  return foo.static
> >foo.static = 0
>   .
>   .
>   .
> My favorite variation is this:
>
>   def accumulator(x):
>   # On first execution, the attribute is not yet known.
>   # This technique allows use of accumulator() as a
>   # function without the "consumer" having to initialize
>   # it.
>   if not "static" in dir(accumulator):
>   accumulator.static = 0
>   accumulator.static += x
>   return accumulator.static
>
>   print accumulator(3)
>   print accumulator(5)

Thanks Cameron, I'll accumulate this in my toolbox.

- pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: singleton decorator

2006-08-08 Thread Paddy

Andre Meyer wrote:

> Am I missing something here? What is the preferred pythonic way of
> implementing singleton elegantly?
>
> Thanks for your help
> André

Hi Andre,
You might also google for
 python borg pattern
As a discussion on the 'borg' design pattern might be informative.

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the cleanest way to compare 2 dictionary?

2006-08-09 Thread Paddy

John Henry wrote:
> Hi list,
>
> I am sure there are many ways of doing comparision but I like to see
> what you would do if you have 2 dictionary sets (containing lots of
> data - like 2 keys and each key contains a dozen or so of records)
> and you want to build a list of differences about these two sets.
>
> I like to end up with 3 lists: what's in A and not in B, what's in B
> and not in A, and of course, what's in both A and B.
>
> What do you think is the cleanest way to do it?  (I am sure you will
> come up with ways that astonishes me  :=) )
>
> Thanks,
I make it 4 bins:
 a_exclusive_keys
 b_exclusive_keys
 common_keys_equal_values
 common_keys_diff_values

Something like:

a={1:1, 2:2,3:3,4:4}
b = {2:2, 3:-3, 5:5}
keya=set(a.keys())
keyb=set(b.keys())
a_xclusive = keya - keyb
b_xclusive = keyb - keya
_common = keya & keyb
common_eq = set(k for k in _common if a[k] == b[k])
common_neq = _common - common_eq


If you now simple set arithmatic, it should read OK.

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the cleanest way to compare 2 dictionary?

2006-08-10 Thread Paddy

John Machin wrote:
> John Henry wrote:
> > Hi list,
> >
> > I am sure there are many ways of doing comparision but I like to see
> > what you would do if you have 2 dictionary sets (containing lots of
> > data - like 2 keys and each key contains a dozen or so of records)
> > and you want to build a list of differences about these two sets.
> >
> > I like to end up with 3 lists: what's in A and not in B, what's in B
> > and not in A, and of course, what's in both A and B.
> >
> > What do you think is the cleanest way to do it?  (I am sure you will
> > come up with ways that astonishes me  :=) )
> >
>
> Paddy has already pointed out a necessary addition to your requirement
> definition: common keys with different values.
>
> Here's another possible addition: you say that "each key contains a
> dozen or so of records". I presume that you mean like this:
>
> a = {1: ['rec1a', 'rec1b'], 42: ['rec42a', 'rec42b']} # "dozen" -> 2 to
> save typing :-)
>
> Now that happens if the other dictionary contains:
>
> b = {1: ['rec1a', 'rec1b'], 42: ['rec42b', 'rec42a']}
>
> Key 42 would be marked as different by Paddy's classification, but the
> values are the same, just not in the same order. How do you want to
> treat that? avalue == bvalue? sorted(avalue) == sorted(bvalue)? Oh, and
> are you sure the buckets don't contain duplicates? Maybe you need
> set(avalue) == set(bvalue). What about 'rec1a' vs 'Rec1a' vs 'REC1A'?
>
> All comparisons are equal, but some comparisons are more equal than
> others :-)
>
> Cheers,
> John

Hi Johns,
The following is my attempt to give more/deeper comparison info.
Assume you have your data parsed and presented as two dicts a and b
each having as values a dict representing a record.
Further assume you have a function that can compute if two record level
dicts  are the same and another function that can compute if two values
in a record level dict are the same.

With a slight modification of my earlier prog we get:

def komparator(a,b, check_equal):
keya=set(a.keys())
keyb=set(b.keys())
a_xclusive = keya - keyb
b_xclusive = keyb - keya
_common = keya & keyb
common_eq = set(k for k in _common if check_equal(a[k],b[k]))
common_neq = _common - common_eq
return (a_xclusive, b_xclusive, common_eq, common_neq)

a_xclusive, b_xclusive, common_eq, common_neq = komparator(a,b,
record_dict__equality_checker)

common_neq = [ (key,
  komparator(a[key],b[key], value__equality_checker)  )
  for key in common_neq ]

Now we get extra info on intra record differences with little extra
code.

Look out though, you could get swamped with data :-)

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the cleanest way to compare 2 dictionary?

2006-08-11 Thread Paddy

I have gone the whole hog and got something thats run-able:

dict_diff.py=

from pprint import pprint as pp

a = {1:{'1':'1'}, 2:{'2':'2'}, 3:dict("AA BB CC".split()), 4:{'4':'4'}}
b = { 2:{'2':'2'}, 3:dict("BB CD EE".split()), 5:{'5':'5'}}
def record_comparator(a,b, check_equal):
keya=set(a.keys())
keyb=set(b.keys())
a_xclusive = keya - keyb
b_xclusive = keyb - keya
_common = keya & keyb
common_eq = set(k for k in _common if check_equal(a[k],b[k]))
common_neq = _common - common_eq
return {"A excl keys":a_xclusive, "B excl keys":b_xclusive,
"Common & eq":common_eq, "Common keys neq
values":common_neq}

comp_result = record_comparator(a,b, dict.__eq__)

# Further dataon common keys, neq values
common_neq = comp_result["Common keys neq values"]
common_neq = [ (key, record_comparator(a[key],b[key], str.__eq__))
   for key in common_neq ]
comp_result["Common keys neq values"] = common_neq

print "\na =",; pp(a)
print "\nb =",; pp(b)
print "\ncomp_result = " ; pp(comp_result)

==

When run it gives:

a ={1: {'1': '1'},
 2: {'2': '2'},
 3: {'A': 'A', 'C': 'C', 'B': 'B'},
 4: {'4': '4'}}

b ={2: {'2': '2'}, 3: {'C': 'D', 'B': 'B', 'E': 'E'}, 5: {'5': '5'}}

comp_result =
{'A excl keys': set([1, 4]),
 'B excl keys': set([5]),
 'Common & eq': set([2]),
 'Common keys neq values': [(3,
 {'A excl keys': set(['A']),
  'B excl keys': set(['E']),
  'Common & eq': set(['B']),
  'Common keys neq values': set(['C'])})]}


- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List match

2006-08-17 Thread Paddy

[EMAIL PROTECTED] wrote:
> OriginalBrownster wrote:
> > Hi there:
> >
> > I know this probably is a very easy thing to do in python, but i wanted
> > to compare 2 lists and generate a new list that does not copy similar
> > entries. An example below
> >
> > list= ["apple", "banana", "grape"]
> > list2=["orange","banana", "pear"]
> >
> > now I want to compare these lits and generate a third list after
> > comparison
> >
> > list3 would be ["apple", "banana","grape","orange", "pear"]
> >
> > hence the double entry would not show up?
> >
> > Is there a way to do this??
> >
> > Stephen
>
> How about:
>
> list3 = list1 + [item for item in list2 if item not in list1]
>
> print list3:
>
> ['apple', 'banana', 'grape', 'orange', 'pear']

It works with the data given, but if list1 contains duplicates...

- Pad

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List match

2006-08-17 Thread Paddy

OriginalBrownster wrote:
> Hi there:
>
> I know this probably is a very easy thing to do in python, but i wanted
> to compare 2 lists and generate a new list that does not copy similar
> entries. An example below
>
> list= ["apple", "banana", "grape"]
> list2=["orange","banana", "pear"]
>
> now I want to compare these lits and generate a third list after
> comparison
>
> list3 would be ["apple", "banana","grape","orange", "pear"]
>
> hence the double entry would not show up?
>
> Is there a way to do this??
>
> Stephen

This solution uses sets; removes all duplicates and is order
preserving.
Remove the outer sorted wrapper if the order need not be preserved.

>>> lst= ["apple", "banana", "grape"]
>>> lst2=["orange","banana", "pear"]
>>> lst3= lst+lst2
>>> sorted([x for x in set(lst3)], key = lambda x: lst3.index(x))
['apple', 'banana', 'grape', 'orange', 'pear']
>>> 

- Paddy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to python

2006-08-17 Thread Paddy

Gallagher, Tim (NE) wrote:
> Hello all,
> I am new to python and I have a few questions.  I am an old Perl hacker
> been using Perl for many years.  I wanted to give python a try, I am
> happy with it so far.
> Question:
> 1. Is there a repository that I can go to for modules? Perl has CPAN and
> I was wondering what the Python equivalent was.
>
> I guess that I had a few more that I cannot think of right now.
>
> Thanks
>
> Tim
Welcome Tim.
The stock answer to the CPAN equivalent question is that Python comes
with a lot more included as standard. You really do need to browse the
Library Reference Docs.
  http://docs.python.org/lib/

You might also want to take a look at this page on the wiki:
  http://wiki.python.org/moin/PerlPhrasebook

Of course, this is as well as going through whatever Python tutorial
you are following.

Have fun, 

- Paddy
.

-- 
http://mail.python.org/mailman/listinfo/python-list


sum and strings

2006-08-17 Thread Paddy
I was browsing the Voidspace blog item on "Flattening Lists", and
followed up on the use of sum to do the flattening.
A solution was:

>>> nestedList = [[1, 2], [3, 4], [5, 6]]
>>> sum(nestedList,[])
[1, 2, 3, 4, 5, 6]

I would not have thought of using sum in this way. When I did help(sum)
the docstring was very number-centric: It went further, and precluded
its use on strings:

>>> help(sum)
Help on built-in function sum in module __builtin__:

sum(...)
sum(sequence, start=0) -> value

Returns the sum of a sequence of numbers (NOT strings) plus the
value
of parameter 'start'.  When the sequence is empty, returns start.

The string preclusion would not help with duck-typing (in general), so
I decided to consult the ref doc on sum:

sum( sequence[, start])

Sums start and the items of a sequence, from left to right, and returns
the total. start defaults to 0. The sequence's items are normally
numbers, and are not allowed to be strings. The fast, correct way to
concatenate sequence of strings is by calling ''.join(sequence). Note
that sum(range(n), m) is equivalent to reduce(operator.add, range(n),
m) New in version 2.3.


The above was a lot better description of sum for me, and with an
inquisitive mind, I like to think that I might have come up with using
sum to flatten nestedList :-)
But there was still that warning about using strings.

I therefore  tried sum versus their reduce "equivalent" for strings:

>>> import operator
>>> reduce(operator.add, "ABCD".split(), '')
'ABCD'
>>> sum("ABCD".split(), '')
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: sum() can't sum strings [use ''.join(seq) instead]
>>>

Well, after all the above, there is a question:

  Why not make sum work for strings too?

It would remove what seems like an arbitrary restriction and aid
duck-typing. If the answer is that the sum optimisations don't work for
the string datatype, then wouldn't it be better to put a trap in the
sum code diverting strings to the reduce equivalent?

Just a thought,

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum and strings

2006-08-18 Thread Paddy
Sybren Stuvel wrote:
> Paddy enlightened us with:
> > Well, after all the above, there is a question:
> >
> >   Why not make sum work for strings too?
>
> Because of "there should only be one way to do it, and that way should
> be obvious". There are already the str.join and unicode.join methods,
> which are more powerful than sum.
>
> Sybren
I get where you are coming from, but in this case we have a function,
sum, that is not as geeral as it could be. sum is already here, and
works for some types but not for strings which seems an arbitrary
limitation that impede duck typing.

- Pad.

P.S. I can see why, and am used to the ''.join method. A newbie
introduced to sum for integers might naturally try and concatenate
strings using sum too.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum and strings

2006-08-18 Thread Paddy

Sybren Stuvel wrote:
> Paddy enlightened us with:
> > Well, after all the above, there is a question:
> >
> >   Why not make sum work for strings too?
>
> Because of "there should only be one way to do it, and that way should
> be obvious". There are already the str.join and unicode.join methods,
> which are more powerful than sum.
>
> Sybren
> --
> The problem with the world is stupidity. Not saying there should be a
> capital punishment for stupidity, but why don't we just take the
> safety labels off of everything and let the problem solve itself?
>  Frank Zappa

Here is where I see the break in the 'flow':

>>> 1+2+3
6
>>> sum([1,2,3], 0)
6
>>> [1] + [2] +[3]
[1, 2, 3]
>>> sum([[1],[2],[3]], [])
[1, 2, 3]
>>> '1' + '2' + '3'
'123'
>>> sum(['1','2','3'], '')
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: sum() can't sum strings [use ''.join(seq) instead]
>>> 

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum and strings

2006-08-18 Thread Paddy

Fredrik Lundh wrote:
> Paddy wrote:
>
> > Here is where I see the break in the 'flow':
> >
> >>>> 1+2+3
> > 6
> >>>> sum([1,2,3], 0)
> > 6
> >>>> [1] + [2] +[3]
> > [1, 2, 3]
> >>>> sum([[1],[2],[3]], [])
> > [1, 2, 3]
> >>>> '1' + '2' + '3'
> > '123'
> >>>> sum(['1','2','3'], '')
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> > TypeError: sum() can't sum strings [use ''.join(seq) instead]
>

Hi Frederik,
> do you often write programs that "sums" various kinds of data types,
> and  for which performance issues are irrelevant?

I was asking if sum was indeed an optimization that did not work for
strings.
I was pointing out its affects on duck-typing.
I was hoping that someone might know the history and implementation of
sum and could point out the design decisions taken at the time and/or
discuss the merits of making sum accept strings. or indeed any type
that works with operator.add and that has an additive identity value.

Pythons designers seem to know and apply the advantages of having fewer
'themes' that can be applied with less constraints I am curious about
such a constraint on sum.

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum and strings

2006-08-18 Thread Paddy

Georg Brandl wrote:
> Paddy wrote:
<>
> > I get where you are coming from, but in this case we have a function,
> > sum, that is not as geeral as it could be. sum is already here, and
> > works for some types but not for strings which seems an arbitrary
> > limitation that impede duck typing.
>
> Only that it isn't arbitrary.
Hi Georg,
I said it *seemed* arbitrary. I doubt that it is arbitrary, and thought
someone would say why the restriction is necessary.

>
> > - Pad.
> >
> > P.S. I can see why, and am used to the ''.join method. A newbie
> > introduced to sum for integers might naturally try and concatenate
> > strings using sum too.
>
> Yes, and he's immediately told what to do instead.
Yep, thats the what. Now as to the why?

- paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum and strings: Summary

2006-08-18 Thread Paddy

Paul Rubin wrote:
> "Paddy" <[EMAIL PROTECTED]> writes:
> > Pythons designers seem to know and apply the advantages of having fewer
> > 'themes' that can be applied with less constraints I am curious about
> > such a constraint on sum.
>
> The opposing argument is that sum is sort of like reduce, i.e.
> sum((a,b,c,d)) could conceivably implemented as
>
>temp = a
>temp += b
>temp += c
>temp += d
>return temp
>
> If the args are strings, the above is a quadratic time algorithm and
> it's better to throw an error than create such a trap for an unwary user.
> The obvious fix is for the manual to specify that the sum function should
> do the right thing and use a sensible algorithm.
>
> Semi-relevant quotation:
>
> "Let's take an example. Consider an abstract data type stack. It's not
> enough to have Push and Pop connected with the axiom wherein you push
> something onto the stack and after you pop the stack you get the same
> thing back. It is of paramount importance that pushing the stack is a
> constant time operation regardless of the size of the stack. If I
> implement the stack so that every time I push it becomes slower and
> slower, no one will want to use this stack.
>
> We need to separate the implementation from the interface but not at
> the cost of totally ignoring complexity. Complexity has to be and is a
> part of the unwritten contract between the module and its user. The
> reason for introducing the notion of abstract data types was to allow
> interchangeable software modules. You cannot have interchangeable
> modules unless these modules share similar complexity behavior. If I
> replace one module with another module with the same functional
> behavior but with different complexity tradeoffs, the user of this
> code will be unpleasantly surprised. I could tell him anything I like
> about data abstraction, and he still would not want to use the
> code. Complexity assertions have to be part of the interface."
>
>   --Alex Stepanov (designer of C++ standard template library)
> http://www.sgi.com/tech/stl/drdobbs-interview.html


Thanks Paul.
I also found this from Guido:
  http://mail.python.org/pipermail/python-dev/2003-April/034853.html
And this, in the same thread:
  http://mail.python.org/pipermail/python-dev/2003-April/034854.html

So,
The upshot is that complexity matters. The algorithm used in sum is
'very wrong' for use with strings, and their is no clean way to switch
to the preferred method for strings.( ''.join() ).


Thanks group,
- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum and strings

2006-08-20 Thread Paddy

Rhamphoryncus wrote:

>
> It's worthwhile to note that the use of + as the concatenation operator
> is arbitrary.  It could just have well been | or &, and has no
> relationship with mathematically addition.

The effect of the string concatenation operator is only secondary.
Secondary to the use of the word sum; and what could be 'reasonably'
concieved as sum's effect on  non-numeric types.
>
> It's also worth stressing (not in response to your post, but others)
> that sum([[1],[2],[3]], []) is just as bad as attempting to sum
> strings, both conceptually (it's not mathematical addition)

Unfortunately, the words sum and summation are linked to other words
that are commonly used to describe what is happening to the numders,
the lists, and the strings.
Words such as accumulate, concatenate, aggregate, collect, assemble, as
well as add.

> and performance-wise.  Don't do it. :)

Amen to that.

> I believe the prefered method to flatten a list of lists is this:
>
> shallow = []
> for i in deep:
> shallow.extend(i)
>
> Yes, it's three lines.  It's also very easy to read.  reduce() and
> sum() are not.

I'd like to squeeze in the listcomp version, not because it is one line
shorter, but because I, and maybe others prefer short listcomps such as
the folowing:

shallow = []
[shallow.extend(i) for i in deep]

-Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expression question

2006-08-21 Thread Paddy

[EMAIL PROTECTED] wrote:
> Hi, I am having some difficulty trying to create a regular expression.

Steve,
I find this tool is great for debugging regular expressions.
  http://kodos.sourceforge.net/

Just put some sample text in one window, your trial RE in another, and
Kodos displays a wealth of information on what matches.

Try it.

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum and strings

2006-08-21 Thread Paddy

Carl Banks wrote:
>
> and, you know, if you really want to concatenate strings with sum, you
> can
>
> class noopadd(object):
> def __add__(self,other):
> return other
> 
> sum(["abc","def","ghi"],noopadd())

;-)

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where is Python in the scheme of things?

2006-10-04 Thread Paddy

gord wrote:
> As a complete novice in the study of Python, I am asking myself where this
> language is superior or better suited than others. For example, all I see in
> the tutorials are lots of examples of list processing, arithmetic
> calculations - all in a DOS-like environment.
>
> What is particularly disappointing is the absence of a Windows IDE,
> components and an event driven paradigm. How does Python stand relative to
> the big 3, namely Visual C++, Visual Basic and Delphi? I realize that these
> programming packages are quite expensive now while Python is free (at least
> for the package I am using - ActivePython).
>
> Please discuss where Python shines.
> Gord

Python is of course superior to all three,
Put together,
With knobs on.

:-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help on pickle tool

2006-10-05 Thread Paddy
virg wrote:
> Hi,
>  i have client-server application which is written in python using
> XMLRPC protocol. The existing client is a command line. Now client
> application we are converting it as Web UI using java. I have seen some
> problems in writing a java client. At the server for each request from
> client, the server sends a response in hashtable and is serialized
> using "pickle". The python function we call at the server is
>
> pickle.dumps(r, 2)  -- where r is a hash table which needs to be
> serialized
>
> At the client (existing client  which in python) we use this call to
> get the original data.
>
> r = pickle.loads(result)
>
> Since i am writing this client as Web UI client using java, i am not
> able to deserialize this data
> using java function "ObjectInputStream" and "ObjectInputStream" which
> are most common functions for deserialization and i getting error as
> invalid header.
>
> Is it possible to deserialize the data by java  which serialized by
> Python or is there any compatibility issue. Is there any equivalent
> pickle tool on java which supports this operation. so that i can use
> across languages.
>
> Because of this problem i am not able to proceed further. Any body has
> any pointers for this problem. Any help is highly appreciated
>
> Thanks in advance
>
> regards
> Virg
You might try picking the data with a different pickle formatter that
your Java can use. Maybe an XML pickler
(http://www.gnosis.cx/download/Gnosis_Utils.More/Gnosis_Utils-1.2.1.ANNOUNCE
untested by me).
You might also use a JSON/YAML pickler. JSON is now a subset of YAML:
  http://cheeseshop.python.org/pypi/python-json/3.4
  http://pyyaml.org/wiki/PyYAML
  http://jyaml.sourceforge.net/
  http://www.yaml.org/
  http://www.json.org/
  http://www.json.org/java/

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help on pickle tool

2006-10-06 Thread Paddy

hanumizzle wrote:
> On 5 Oct 2006 22:25:58 -0700, Paddy <[EMAIL PROTECTED]> wrote:
>
> > You might try picking the data with a different pickle formatter that
> > your Java can use. Maybe an XML pickler
> > (http://www.gnosis.cx/download/Gnosis_Utils.More/Gnosis_Utils-1.2.1.ANNOUNCE
> > untested by me).
> > You might also use a JSON/YAML pickler. JSON is now a subset of YAML:

>
> Why a subset?

I was referring to comments ike:
  http://redhanded.hobix.com/inspect/yamlIsJson.html

http://redhanded.hobix.com/inspect/jsonCloserToYamlButNoCigarThanksAlotWhitespace.html

Happy coding - Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help on pickle tool

2006-10-06 Thread Paddy

Paddy wrote:
> hanumizzle wrote:
> > On 5 Oct 2006 22:25:58 -0700, Paddy <[EMAIL PROTECTED]> wrote:
> >
> > > You might try picking the data with a different pickle formatter that
> > > your Java can use. Maybe an XML pickler
> > > (http://www.gnosis.cx/download/Gnosis_Utils.More/Gnosis_Utils-1.2.1.ANNOUNCE
> > > untested by me).
> > > You might also use a JSON/YAML pickler. JSON is now a subset of YAML:
>
> >
> > Why a subset?
>
> I was referring to comments ike:
>   http://redhanded.hobix.com/inspect/yamlIsJson.html
>
> http://redhanded.hobix.com/inspect/jsonCloserToYamlButNoCigarThanksAlotWhitespace.html
>
> Happy coding - Paddy.

Oh, and this might also be of use:

http://www-128.ibm.com/developerworks/web/library/x-matters46/index.html

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extract certain values from file with re

2006-10-06 Thread Paddy

Fabian Braennstroem wrote:
> Hi,
>
>
> I actually want to extract the lines with the numbers, write
> them to a file and finally use gnuplot for plotting them. A
> nicer and more python way would be to extract those numbers,
> write them into an array according to their column and plot
> those using the gnuplot or matplotlib module :-)
>

You might try comparing Ploticus to Gnuplot for your graph plotting
  http://ploticus.sourceforge.net/

... but if you already know gnuplot, and it does what you want then ...

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: n-body problem at shootout.alioth.debian.org

2006-10-06 Thread Paddy

[EMAIL PROTECTED] wrote:
> [EMAIL PROTECTED] wrote:
> > Ah, wait a moment.  One more tweak.  Make the body class a psyco class.
> > That improves the runtime to 3.02s.  Diff appended.
>
> Nice. Maybe you can do the same trick with:
> from psyco.classes import __metaclass__
>
> If you want you can try that trick with this version of mine:
> http://shootout.alioth.debian.org/sandbox/benchmark.php?test=nbody&lang=psyco&id=3
>
> (I can't try it, precompiled Psyco doesn't exists yet for Py2.5). If
> it's faster, then I can upload some modified version...
>
> Bye,
> bearophile

You might also put the outer loop calling function advance so many
times, into the advance function:

==
def advance(bodies, dt, n) :
for i in xrange(n) :
for i,b in enumerate(bodies) :

...

def main() :
...
advance(bodies, 0.01, n)

==

This I like. It points to areas of python where maybe we should be
adding to the standard library whilst also showing off the cream of the
non-standard libraries out their.

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie - Stuck

2006-10-08 Thread Paddy
[EMAIL PROTECTED] wrote:
> The perl version of this code works but not the python version. What am
> I doing wrong?
>
> message = "abc"
> password = "z12"
>
> scrambled = message ^ password
>
> I also wondered why this errored as well...
>
> int(messege)
>
> Is it not meant to convert a string to a number?
Hmm,
Looks like you need to learn more elementary Python before we can even
attempt to help you more, but here goes anyway...

Python has strict typing compared to Perl (a good thing)!
The string "abc" is not a valid representation of an integer in Python,
 and, unlike Perl, Python will complain about its use when an integer
is expected:

$ perl -e 'print "abc" ^ 123, "\n"'
123

$ python -c 'print "abc" ^ 123'
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unsupported operand type(s) for ^: 'str' and 'int'

$

Please don't give up on Python. It *is* different to Perl. 

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Starting out.

2006-10-12 Thread Paddy
Ahmer wrote:
> Hi all!
>
> I am a 15 year old High School Sophomore. I would like to start
> programming in Python. In school, we are learning Java (5) and I like
> to use the Eclipse IDE, I also am learning PHP as well.
>
> What are some ways to get started (books, sites, etc.)? I am usually on
> linux, but I have a windows box and am planning on getting a mac.

Pydev gives you a Python mode for Eclipse:
  http://pydev.sourceforge.net/
The Python tutorial is a good way to learn Python:
  http://docs.python.org/tut/
Some pointers on writing Python for Java programmers:
  http://www.ferg.org/projects/python_java_side-by-side.html
I guess you are new to both Java and Python, but if you know Java and
were starting Python, the following points out that certain idioms of
Java do not translate well to Python:
  http://dirtsimple.org/2004/12/python-is-not-java.html

And finally: Lets 'big-up' Python:
  http://www.paulgraham.com/pypar.html

I hope you enjoy Python.
All the best,  Paddy.


P.S. maybe your High school might be interested in teaching Python as a
first language rather than Java?
  http://www.oreilly.com/pub/a/oreilly/frank/elkner_0300.html

http://www.python.org/workshops/2000-01/proceedings/papers/elkner/pyYHS.html

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loops Control with Python

2006-10-13 Thread Paddy

Wijaya Edward wrote:
> Can we make loops control in Python?
> What I mean is that whether we can control
> which loops to exit/skip at the given scope.
>
> For example in Perl we can do something like:
>
> OUT:
> foreach my $s1 ( 0 ...100) {
>
> IN:
> foreach my $s2 (@array) {
>
>   if ($s1 == $s2) {
>  next OUT;
>   }
>   else {
>   last IN;
>   }
>
>  }
> }
>
> How can we implement that construct with Python?
>

Python does not use Labels. If you want to quit a single loop then look
up the Python break statement. If you want to exit deeply nested
execution then Python has exceptions. this maybe new to a Perl
programmer so please take time to understand Python exceptions.

There follows a function that you can call from an interactive session
to explore one type of use for exceptions  that is rather like your use
of Perl labels shown.

==
class Outer(Exception):
  pass
class Inner(Exception):
  pass

def skip_loops(y1 = -1, y2 = -1, y3 = -1):
  ''' Shows how to skip parts of nested loops in Python'''
  try:
for x0 in range(3):
  try:
for x1 in range(3):
  for x2 in range(3):
if x2 == y2:
  raise Inner
if x2 == y3:
  break
print (x0,x1,x2)
  if x1 == y1:
raise Outer
  print (x0,x1)
  except Inner:
print "Raised exception Inner"
  print (x0,)
  except Outer:
print "Raised exception Outer"

==

>>> skip_loops(y1=2)
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 0)
(0, 1, 0)
(0, 1, 1)
(0, 1, 2)
(0, 1)
(0, 2, 0)
(0, 2, 1)
(0, 2, 2)
Raised exception Outer
>>> skip_loops(y2=2)
(0, 0, 0)
(0, 0, 1)
Raised exception Inner
(0,)
(1, 0, 0)
(1, 0, 1)
Raised exception Inner
(1,)
(2, 0, 0)
(2, 0, 1)
Raised exception Inner
(2,)
>>> 


- Paddy.
P.S. Welcome to Python!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loops Control with Python

2006-10-13 Thread Paddy

hg wrote:
> Paddy wrote:
> > P.S. Welcome to Python!
> >
> How about a thread on GOTOs ? ;-)

I'm trying to be nice on c.l.p.
- Mind you, I do have that rant as part of my blog:
  http://paddy3118.blogspot.com/2006/03/whats-wrong-with-perl.html

;-)

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Standard Forth versus Python: a case study

2006-10-13 Thread Paddy
werty wrote:
> Apples/oranges ?   programmers are making very little $$ today .
>Thats software !   No one is makin money on obsolete Forth ,
> so why a comparisom ?
>
>   Ultimately the best OpSys will be free and  millions of lines of code
>  obsoleted .  Because no one can protect intellectual property , its
> simply too costly for a Government to do this .
>
>   Notice the crypto fiasco , the USA govt forbad export of SSL and
> in short order Australia gave the world a free SSLeasy !
>
>This is software .  No one will , for long , own software .
>  Microsoft and Linux will die in 24 months .   No hardware will
> produce money/profits using them .
>
>   Because we have a new hardware competitor , that obsoletes the BIOS
>  chip , North bridge/South bridge USB helpers , NICs .
>   No mo PNP (Plug_and_Pray) .
>   In 2 chips ( CPU /SoC and LCD controller) it will be faster than
>  a PC .  100's have allready written HDD drivers and haven't yet
>  free'd them .  But when others give free , what good do it to
>  hold yours !You look stupid selling what others improve and
> free .   Trying to sell what others find easy to create !
>   Intel made hardware too hard to program , ARM is easy .
>   Python wont last on ARM , for WCE and Linux will be tossed .
>   A simpler structured method will be used to customise
>   Browsers . There will be 2 columns , one on left will be main/orig
> but on the Right will have hyperlink result .  This way ya dont have
>  to go back to compare !   side by side .
>   Text editors will also work this way . You will read orig in left
> columns
>  and 'edit'/annotate  your stuff to the Right columns .
>
>   Sun microsystems et all ( the ones we seldom think about ) will
>  all be obsoleted , bankrupted , their hardware surplused .
>   No more h/w servers .
>  There will be no high speed 64 bit boxes in the future .
>   The Pocket PC will do work you could not  imagine !
>   All will have 100 GB HDD , VGA LCD , USBH/USBD , WIFI N
>   and no WERTY  keyboard !  full GUI ...
>   ethernet and firewire and rs232 will die
>
>   Why not "see" the future ?
>  No Linux ,no WXP , no C+ , no PC .

Hah! This is the output from a program and I claim my prize.
:-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: terminate execfile

2006-10-14 Thread Paddy

Teja wrote:
> Teja wrote:
>
> > How to terminate execfile() in the middle of its execution. Any
> > pointers ???
> > Its very urgent please
> >
> >
> > Thanks
> > Teja.P
>
> Can I raise an interrupt using PyErr_SetInterrupt??? Is so , does any
> one know how to do it?
I presume there is only one thread of execution here, so the file being
execfiled would have to recognise an error condition and raise an
un-caught exception.

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with the 'math' module in 2.5?

2006-10-15 Thread Paddy

Ben Finney wrote:
> "Chris" <[EMAIL PROTECTED]> writes:
>
> > Oh, ok that explains it. Is that why my 16-bit calculator gives me
> > 0?
>
> Your calculator is probably doing rounding without you asking for it.
>
> Python refuses to guess what you want, and gives you the information
> available.
>
Hi Ben,
I don't think Python should take too much credit here. Floating point
calcuations are subject to rounding. Sometimes it shows.

- Pad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use python in TestMaker

2006-10-18 Thread Paddy

kelin,[EMAIL PROTECTED] wrote:
> Hello,
>
> Now I 'm learning python to do testing jobs, and want to use it in
> TestMaker.
> The problem is: I don't know how to use python in TestMaker.
> Just write python program in it or call .py files in it?
> I am really new about it and need some help.
> 
> Thanks a lot!
What/where is TestMaker?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why does this unpacking work

2006-10-20 Thread Paddy
John Salerno wrote:
> I'm a little confused, but I'm sure this is something trivial. I'm
> confused about why this works:
>
>  >>> t = (('hello', 'goodbye'),
>   ('more', 'less'),
>   ('something', 'nothing'),
>   ('good', 'bad'))
>  >>> t
> (('hello', 'goodbye'), ('more', 'less'), ('something', 'nothing'),
> ('good', 'bad'))
>  >>> for x in t:
>   print x
>
>
> ('hello', 'goodbye')
> ('more', 'less')
> ('something', 'nothing')
> ('good', 'bad')
>  >>> for x,y in t:
>   print x,y
>
>
> hello goodbye
> more less
> something nothing
> good bad
>  >>>
>
> I understand that t returns a single tuple that contains other tuples.
> Then 'for x in t' returns the nested tuples themselves.
>
> But what I don't understand is why you can use 'for x,y in t' when t
> really only returns one thing. I see that this works, but I can't quite
> conceptualize how. I thought 'for x,y in t' would only work if t
> returned a two-tuple, which it doesn't.
>

Hi John,

Thats the point were you go astray.
iterating over t *does* produce a 2-tuple that can be unpacked
immediately.

maybe this will help, (notice that element is always one of the inner
tuples):

>>> tpl = ((00,01), (10,11), (20,21))
>>> for element in tpl:
... print "tpl provides this when iterated over:", element
...
tpl provides this when iterated over: (0, 1)
tpl provides this when iterated over: (10, 11)
tpl provides this when iterated over: (20, 21)
>>> for element in tpl:
... print "tpl provides this when iterated over:", element
... sub0, sub1 = element
... print "each element unpacks to:", sub0,"and:", sub1
...
tpl provides this when iterated over: (0, 1)
each element unpacks to: 0 and: 1
tpl provides this when iterated over: (10, 11)
each element unpacks to: 10 and: 11
tpl provides this when iterated over: (20, 21)
each element unpacks to: 20 and: 21
>>> for sub0, sub1 in tpl:
... print "each element of tuple unpacked immediately to:",
sub0,"and:", sub1
...
each element of tuple unpacked immediately to: 0 and: 1
each element of tuple unpacked immediately to: 10 and: 11
each element of tuple unpacked immediately to: 20 and: 21
>>> 


- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   >