Re: Symbols as parameters?

2010-01-21 Thread Andre Engels
On Thu, Jan 21, 2010 at 8:43 AM, Martin Drautzburg
 wrote:
> Hello all,
>
> When passing parameters to a function, you sometimes need a paramter
> which can only assume certain values, e.g.
>
>        def move (direction):
>                ...
> If direction can only be "up", "down", "left" or "right", you can solve
> this by passing strings, but this is not quite to the point:
>
>        - you could pass invalid strings easily
>        - you need to quote thigs, which is a nuisance
>        - the parameter IS REALLY NOT A STRING, but a direction
>
> Alternatively you could export such symbols, so when you "import *" you
> have them available in the caller's namespace. But that forces you
> to "import *" which pollutes your namespace.
>
> What I am really looking for is a way
>
>        - to be able to call move(up)
>        - having the "up" symbol only in the context of the function call
>
> So it should look something like this
>
> ... magic, magic ...
> move(up)
> ... unmagic, unmagic ...
> print up
>
> This should complain that "up" is not defined during the "print" call,
> but not when move() is called. And of course there should be as little
> magic as possible.
>
> Any way to achieve this?

It probably can be done, but in my opinion even it can, it would be
ugly. I would just define "up" as some global constant - I don't see
why it would be a problem that it's defined when you don't need it. In
fact, I think it would be beneficial - you can then have
direction-valued variables, so that you can (for example) implement
"go the same direction I went last time". If that kind of thing
happens more often, it might be useful to have a Direction class, to
be able to easily program in things like "the opposite of up is down"
and "right from right is back".



-- 
André Engels, andreeng...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: html code generation

2010-01-21 Thread John Nagle

George Trojan wrote:
I need an advice on table generation. The table is essentially a fifo, 
containing about 200 rows. The rows are inserted every few minutes or 
so. The simplest solution is to store row data per line and write 
directly html code:

line = "value1value2>... "
each run of the program would read the previous table into a list of 
lines, insert the first row and drop the last one, taking care of table 
header and trailer.

Is there a more classy solution?

George


  The "HTMLTemplate" module is good for simple tasks like that.
There are much more elaborate frameworks available, but if all you
need to do is build a table periodically, it's a simple solution.

   This page

http://www.sitetruth.com/reports/phishes.html

   is built with HTMLtemplate.  It changes only every three hours,
and computing it requires a big SQL join, so it's an automatically
updated static page.

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


Re: Sorted dictionary

2010-01-21 Thread Raymond Hettinger
On Jan 20, 5:02 pm, "Jan Kaliszewski"  wrote:
> Hello,
>
> Inspired by some my needs as well as some discussions in the net, I've  
> implemented a sorted dictionary (i.e. a dict that returns keys, values and  
> items always sorted by keys):
>
> http://code.activestate.com/recipes/576998/
>
> Maybe it'll appear to be useful for somebody... And I'm curious about your  
> opinions.

Using an underlying list to track sorted items
means that insertion and deletion take O(n) time.
That could be reduced to O(log n) time by using
a blist or skiplist as the underlying structure
for maintaining a sort.

The other alternative is to just append items to the list
and sort the list on demand.  Since the Timsort takes advantage
of existing order, the process will approach O(n) if sorting
after every few updates.  This is close the O(n) time it takes
to iterate the list in the first place:

   s = SortedDict(items)
   list(s)   # O(n log n) to sort and O(n) to iterate
   s[newkey] = newval
   list(s)   # close to O(n)

my two cents,


Raymond

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


Re: Symbols as parameters?

2010-01-21 Thread Alf P. Steinbach

* Martin Drautzburg:

Hello all,

When passing parameters to a function, you sometimes need a paramter
which can only assume certain values, e.g.

def move (direction):
...
If direction can only be "up", "down", "left" or "right", you can solve
this by passing strings, but this is not quite to the point:

- you could pass invalid strings easily
- you need to quote thigs, which is a nuisance
- the parameter IS REALLY NOT A STRING, but a direction

Alternatively you could export such symbols, so when you "import *" you
have them available in the caller's namespace. But that forces you
to "import *" which pollutes your namespace.

What I am really looking for is a way

- to be able to call move(up)
- having the "up" symbol only in the context of the function call

So it should look something like this

... magic, magic ...
move(up)
... unmagic, unmagic ...
print up

This should complain that "up" is not defined during the "print" call,
but not when move() is called. And of course there should be as little
magic as possible.

Any way to achieve this?


>>> def move( direction ):
...   print( "move " + str( direction ) )
...
>>> move( "up" )
move up
>>>
>>> class using_directions:
... up = 42
... move( up )
...
move 42
>>> up
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'up' is not defined
>>> _


Of course it's an abuse of the language. :-)

So I wouldn't recommend it, but it's perhaps worth having seen it.


Cheers & hth.,

- Alf

PS: I hope this was not a homework question.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Symbols as parameters?

2010-01-21 Thread Javier Collado
Hello,

I'd say that isn't totally incorrect to use strings instead of
symbols. Please note that in other programming languages symbols,
atoms and the like are in fact immutable strings, which is what python
provides by default.

Best regards,
Javier

2010/1/21 Alf P. Steinbach :
> * Martin Drautzburg:
>>
>> Hello all,
>>
>> When passing parameters to a function, you sometimes need a paramter
>> which can only assume certain values, e.g.
>>
>>        def move (direction):
>>                ...
>> If direction can only be "up", "down", "left" or "right", you can solve
>> this by passing strings, but this is not quite to the point:
>>
>>        - you could pass invalid strings easily
>>        - you need to quote thigs, which is a nuisance
>>        - the parameter IS REALLY NOT A STRING, but a direction
>>
>> Alternatively you could export such symbols, so when you "import *" you
>> have them available in the caller's namespace. But that forces you
>> to "import *" which pollutes your namespace.
>>
>> What I am really looking for is a way
>>
>>        - to be able to call move(up)
>>        - having the "up" symbol only in the context of the function call
>>
>> So it should look something like this
>>
>> ... magic, magic ...
>> move(up)
>> ... unmagic, unmagic ...
>> print up
>>
>> This should complain that "up" is not defined during the "print" call,
>> but not when move() is called. And of course there should be as little
>> magic as possible.
>>
>> Any way to achieve this?
>
 def move( direction ):
> ...   print( "move " + str( direction ) )
> ...
 move( "up" )
> move up

 class using_directions:
> ...     up = 42
> ...     move( up )
> ...
> move 42
 up
> Traceback (most recent call last):
>  File "", line 1, in 
> NameError: name 'up' is not defined
 _
>
>
> Of course it's an abuse of the language. :-)
>
> So I wouldn't recommend it, but it's perhaps worth having seen it.
>
>
> Cheers & hth.,
>
> - Alf
>
> PS: I hope this was not a homework question.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Symbols as parameters?

2010-01-21 Thread Ben Finney
Martin Drautzburg  writes:

> When passing parameters to a function, you sometimes need a paramter
> which can only assume certain values

You might like to try the ‘enum’ library for this
http://pypi.python.org/pypi/enum>.

-- 
 \   “You could augment an earwig to the point where it understood |
  `\ nuclear physics, but it would still be a very stupid thing to |
_o__)  do!” —The Doctor, _The Two Doctors_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Symbols as parameters?

2010-01-21 Thread Bearophile
Martin Drautzburg, having symbols spread in the namespace is bad. And
too much magic is even worse. You seem to need something like an enum
that must be used with its qualified name, as:
move(direction.up)
That works well unless the symbols name are keywords.

Creating a small class like this (that warns if you give it a string
that contains a keyword) looks not too much hard:
direction = Enum("up", "down", "left", "right")
Or:
direction = Enum("up, down, left, right")
Or:
direction = Enum("up down left right")

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorted dictionary

2010-01-21 Thread Bearophile
Raymond Hettinger:
> Using an underlying list to track sorted items
> means that insertion and deletion take O(n) time.
> That could be reduced to O(log n) time by using
> a blist or skiplist as the underlying structure
> for maintaining a sort.

In the collections module it can be useful to have ordered dicts and
sets based on search trees.
I'm thinking about B+ trees to use CPU cache locality better. It can
be fun :-)

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Symbols as parameters?

2010-01-21 Thread Iain King
On Jan 21, 7:43 am, Martin Drautzburg 
wrote:
> Hello all,
>
> When passing parameters to a function, you sometimes need a paramter
> which can only assume certain values, e.g.
>
>         def move (direction):
>                 ...
> If direction can only be "up", "down", "left" or "right", you can solve
> this by passing strings, but this is not quite to the point:
>
>         - you could pass invalid strings easily
>         - you need to quote thigs, which is a nuisance
>         - the parameter IS REALLY NOT A STRING, but a direction
>
> Alternatively you could export such symbols, so when you "import *" you
> have them available in the caller's namespace. But that forces you
> to "import *" which pollutes your namespace.
>
> What I am really looking for is a way
>
>         - to be able to call move(up)
>         - having the "up" symbol only in the context of the function call
>
> So it should look something like this
>
> ... magic, magic ...
> move(up)
> ... unmagic, unmagic ...
> print up
>
> This should complain that "up" is not defined during the "print" call,
> but not when move() is called. And of course there should be as little
> magic as possible.
>
> Any way to achieve this?

class Direction(object):
  pass

def is_direction(d):
  return type(d)==Direction

up = Direction()
down = Direction()
left = Direction()
right = Direction()

Now you can do your move(up), print up, etc. You can also check a
valid direction was passed in by calling is_direction.  'Course, you
can extend this so it does something a little more useful:

class Direction(object):
  def __init__(self, vx=0, vy=0):
self.vx = vx
self.vy = vy

up = Direction(0, -1)
down = Direction(0, 1)
left = Direction(-1, 0)
right = Direction(1, 0)

def move(direction):
  spaceship.x += direction.vx
  spaceship.y += direction.vy

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


Re: Symbols as parameters?

2010-01-21 Thread Alf P. Steinbach

Huh? I guess you meant to reply to the OP, not me.

Cheers,

- Alf

* Javier Collado:

Hello,

I'd say that isn't totally incorrect to use strings instead of
symbols. Please note that in other programming languages symbols,
atoms and the like are in fact immutable strings, which is what python
provides by default.

Best regards,
Javier

2010/1/21 Alf P. Steinbach :

* Martin Drautzburg:

Hello all,

When passing parameters to a function, you sometimes need a paramter
which can only assume certain values, e.g.

   def move (direction):
   ...
If direction can only be "up", "down", "left" or "right", you can solve
this by passing strings, but this is not quite to the point:

   - you could pass invalid strings easily
   - you need to quote thigs, which is a nuisance
   - the parameter IS REALLY NOT A STRING, but a direction

Alternatively you could export such symbols, so when you "import *" you
have them available in the caller's namespace. But that forces you
to "import *" which pollutes your namespace.

What I am really looking for is a way

   - to be able to call move(up)
   - having the "up" symbol only in the context of the function call

So it should look something like this

... magic, magic ...
move(up)
... unmagic, unmagic ...
print up

This should complain that "up" is not defined during the "print" call,
but not when move() is called. And of course there should be as little
magic as possible.

Any way to achieve this?

def move( direction ):

...   print( "move " + str( direction ) )
...

move( "up" )

move up

class using_directions:

... up = 42
... move( up )
...
move 42

up

Traceback (most recent call last):
 File "", line 1, in 
NameError: name 'up' is not defined

_


Of course it's an abuse of the language. :-)

So I wouldn't recommend it, but it's perhaps worth having seen it.


Cheers & hth.,

- Alf

PS: I hope this was not a homework question.
--
http://mail.python.org/mailman/listinfo/python-list


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


deleting, then re-importing a class method

2010-01-21 Thread Robert P. J. Day

  (once again, never ashamed to ask the dumb questions.)

  still playing with python3, and testing whether i can
delete/unimport a specific method, then re-import it:

>>> import sys
>>> print(sys.__doc__)
... blah blah blah ...
>>> del(sys.__doc__)
>>> print(sys.__doc__)
module(name[, doc])

Create a module object.
The name must be a string; the optional doc argument can have any
type.
>>>

  ok, now that i've deleted just that member of "sys", can i re-import
it?  i know this doesn't seem to work:

>>> import sys

  or is there an operator other than "import" that more represents a
full refresh of a class?

rday

p.s.  no, i don't have a valid application of the above, i'm just
trying to break things.

--



Robert P. J. Day   Waterloo, Ontario, CANADA

Linux Consulting, Training and Kernel Pedantry.

Web page:  http://crashcourse.ca
Twitter:   http://twitter.com/rpjday

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


Re: why the super class can access the subclass's attribute

2010-01-21 Thread Jean-Michel Pichavant

yousay wrote:

I have sees aprogram like this ,i confusing why super class can access
the subclass's attribute
,this is the program,thanks in advance:
class MyThread(threading.Thread):
def join(self):
super(MyThread,self).join()
return self.result

class Worker(MyThread):
import random
import pdb
pdb.set_trace()
def run(self):
total = 0
for i in range(random.randrange(10,100)):
total +=i
self.result = total


  

I don't thing I got your problem.
But in case  you are talking about 'result', you could probably say that 
"the subclass Worker can access to the super class MyThread 'result' 
attribute".


Also keep in mind that there is no private attributes in python, and 
that any object can access any other object attribute, no matter its 
class. Of course, you dont want to do that.


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


subprocess troubles

2010-01-21 Thread Tomas Pelka

Hey all,

have a problem with following piece of code:

--
import subprocess

paattern = "python"
cmd = "/usr/bin/locate"
arg1 = " -i"
arg2 = " -d /var/www/books/mlocate.db"
arg3 = str(" " + pattern)

p1 = subprocess.Popen([cmd, arg1, arg2, arg3], shell=False, 
stdout=subprocess.PIPE, stderr=subprocess.PIPE)

(stdoutdata, stderrdata) = p1.communicate()

print p1.returncode
print "%s -- %s" % (stdoutdata, stderrdata)
--

But return code is always 1 and command do not return any result/error 
(stdoutdata, stderrdata are None). If I run this command 
(/usr/bin/locate -i -d /var/www/books/mlocate.db python) from standard 
shell everything goes fine.


Could you please give me an advice what I'm doing wrong?

Thanks
Cheers

--
Tom

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


Re: Symbols as parameters?

2010-01-21 Thread Carl Banks
On Jan 20, 11:43 pm, Martin Drautzburg 
wrote:
> Hello all,
>
> When passing parameters to a function, you sometimes need a paramter
> which can only assume certain values, e.g.
>
>         def move (direction):
>                 ...
> If direction can only be "up", "down", "left" or "right", you can solve
> this by passing strings, but this is not quite to the point:
>
>         - you could pass invalid strings easily
>         - you need to quote thigs, which is a nuisance
>         - the parameter IS REALLY NOT A STRING, but a direction

Nothing you can pass to the function is really a direction.  A symbol
is no more a direction than a string is.


> Alternatively you could export such symbols, so when you "import *" you
> have them available in the caller's namespace. But that forces you
> to "import *" which pollutes your namespace.

No it doesn't.  You can still write module.UP in the function call, or
you can write from module import UP.


> What I am really looking for is a way
>
>         - to be able to call move(up)
>         - having the "up" symbol only in the context of the function call

Short answer is, you can't do it.

Long answer is, you don't really want to have a symbol that's only in
context during the function call, because you might just want to write
some code that operates on directions (e.g., return random.choice
([UP,DOWN]), but it's a moot point since you can't do it.

> So it should look something like this
>
> ... magic, magic ...
> move(up)
> ... unmagic, unmagic ...
> print up
>
> This should complain that "up" is not defined during the "print" call,
> but not when move() is called. And of course there should be as little
> magic as possible.
>
> Any way to achieve this?

Apart from writing a custom DSL (domain specific language), no.

It is not, in case your were wondering, a feature that would be easily
added to Python (the moratorium on new syntax notwithstanding).
Python wouldn't be able to do this at compile time (since Python
doesn't know what symbols refer to till run time).  I convinced myself
that it would be techincally possible to do it at run time, but at a
penalty of higher function call overhead (which is already high enough
as it is).  And with the performance hit, extra scoping complexity,
the inability to be used outside the function context, and no real
benefit except to save typing, I don't see it ever being approved.


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


Re: subprocess troubles

2010-01-21 Thread Javier Collado
Hello,

If you set shell=False, then I think that arg2 should be separated
into two different parts.

Also, arg3 could be set just to pattern (no need to add extra spaces
or using str function).

Best regards,
Javier

2010/1/21 Tomas Pelka :
> Hey all,
>
> have a problem with following piece of code:
>
> --
> import subprocess
>
> paattern = "python"
> cmd = "/usr/bin/locate"
> arg1 = " -i"
> arg2 = " -d /var/www/books/mlocate.db"
> arg3 = str(" " + pattern)
>
> p1 = subprocess.Popen([cmd, arg1, arg2, arg3], shell=False,
> stdout=subprocess.PIPE, stderr=subprocess.PIPE)
> (stdoutdata, stderrdata) = p1.communicate()
>
> print p1.returncode
> print "%s -- %s" % (stdoutdata, stderrdata)
> --
>
> But return code is always 1 and command do not return any result/error
> (stdoutdata, stderrdata are None). If I run this command (/usr/bin/locate -i
> -d /var/www/books/mlocate.db python) from standard shell everything goes
> fine.
>
> Could you please give me an advice what I'm doing wrong?
>
> Thanks
> Cheers
>
> --
> Tom
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Symbols as parameters?

2010-01-21 Thread Alf P. Steinbach

* Carl Banks:

On Jan 20, 11:43 pm, Martin Drautzburg 

[snip]



What I am really looking for is a way

- to be able to call move(up)
- having the "up" symbol only in the context of the function call


Short answer is, you can't do it.



On the contrary, it's not difficult to do.

I provided an example in my answer to the OP (first reply in the thread).

However, it's IMHO an abuse of the language, not something that one should do.


Cheers & hth.,

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


Re: deleting, then re-importing a class method

2010-01-21 Thread Jean-Michel Pichavant

Robert P. J. Day wrote:

  (once again, never ashamed to ask the dumb questions.)

  still playing with python3, and testing whether i can
delete/unimport a specific method, then re-import it:

  

import sys
print(sys.__doc__)


... blah blah blah ...
  

del(sys.__doc__)
print(sys.__doc__)


module(name[, doc])

Create a module object.
The name must be a string; the optional doc argument can have any
type.
  


  ok, now that i've deleted just that member of "sys", can i re-import
it?  i know this doesn't seem to work:

  

import sys



  or is there an operator other than "import" that more represents a
full refresh of a class?

rday

p.s.  no, i don't have a valid application of the above, i'm just
trying to break things.

--



Robert P. J. Day   Waterloo, Ontario, CANADA

Linux Consulting, Training and Kernel Pedantry.

Web page:  http://crashcourse.ca
Twitter:   http://twitter.com/rpjday

  

reload(sys)

JM


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


Re: deleting, then re-importing a class method

2010-01-21 Thread Peter Otten
Robert P. J. Day wrote:

> 
>   (once again, never ashamed to ask the dumb questions.)
> 
>   still playing with python3, and testing whether i can
> delete/unimport a specific method, then re-import it:
> 
 import sys
 print(sys.__doc__)
> ... blah blah blah ...
 del(sys.__doc__)
 print(sys.__doc__)
> module(name[, doc])
> 
> Create a module object.
> The name must be a string; the optional doc argument can have any
> type.

> 
>   ok, now that i've deleted just that member of "sys", can i re-import
> it?  i know this doesn't seem to work:

Actually you haven't:

>>> import sys
>>> del sys.__doc__
>>> hasattr(sys, "__doc__")
True

> 
 import sys
> 
>   or is there an operator other than "import" that more represents a
> full refresh of a class?

imp.reload()

> rday
> 
> p.s.  no, i don't have a valid application of the above, i'm just
> trying to break things.

That is indeed likely to happen:

Python 3.1.1+ (r311:74480, Nov  2 2009, 15:45:00)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> walk = os.walk
>>> del os.walk
>>> hasattr(os, "walk")
False
>>> import imp
>>> imp.reload(os)

>>> os.walk

>>> os.walk is walk
False

So you have to two distinct walk() functions now. This becomes especially 
nasty when

isinstance(obj, module.Class)

tests begin to fail because the module and the class was reloaded, but obj 
is an instance of module.Class before the reload.

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


Re: Symbols as parameters?

2010-01-21 Thread Jean-Michel Pichavant

Martin Drautzburg wrote:

Hello all,

When passing parameters to a function, you sometimes need a paramter
which can only assume certain values, e.g.

def move (direction):
...
If direction can only be "up", "down", "left" or "right", you can solve
this by passing strings, but this is not quite to the point:

- you could pass invalid strings easily
- you need to quote thigs, which is a nuisance
- the parameter IS REALLY NOT A STRING, but a direction

Alternatively you could export such symbols, so when you "import *" you
have them available in the caller's namespace. But that forces you
to "import *" which pollutes your namespace.

What I am really looking for is a way

- to be able to call move(up)
- having the "up" symbol only in the context of the function call

So it should look something like this

... magic, magic ...
move(up)
... unmagic, unmagic ...
print up

This should complain that "up" is not defined during the "print" call,
but not when move() is called. And of course there should be as little
magic as possible.

Any way to achieve this?

  

in move.py

def move(direction):
   print "moving %s" % direction

move.UP = 'up'
move.DOWN = 'down'

Then

>>> from move import move
>>> move(move.UP)
moving up


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


Re: Best way to convert sequence of bytes to long integer

2010-01-21 Thread Helmut Jarausch

On 01/20/10 22:23, Steven D'Aprano wrote:


I'm writing a module that handles, I won't call it encryption,
obfuscation using classical cryptographic algorithms. One of the
functions needs a deterministic but unpredictable integer generated from
a human-generated password or passphrase, so I'm using:

hashlib.md5(key).digest()

to get a string of bytes, then converting it to an int.

int.from_bytes would be perfect for me, but in the meantime I'm using
Paul Rubin's trick of int(s.encode("hex"), 16).



Sorry, but this doesn't work for me (in Python 3.2a0)
since hashlib.md5(key).digest() returns a byte string
which has no .encode method.

Just my 5 cents,
Helmut.


--
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
--
http://mail.python.org/mailman/listinfo/python-list


covert number into string

2010-01-21 Thread anusha k
Hi,

Can anyone tell me how to convert number to words
For example:
If number = then it should give me *Nine thousand nine hundred
ninetynine*
Is there any build-in function or something that can do this for me
Thank you in advance
Anusha Kadambala
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Symbols as parameters?

2010-01-21 Thread Stefan Behnel
Alf P. Steinbach, 21.01.2010 09:30:
> * Martin Drautzburg:
>> - to be able to call move(up)
>> - having the "up" symbol only in the context of the function call
>>
>> So it should look something like this
>>
>> ... magic, magic ...
>> move(up)
>> ... unmagic, unmagic ...
>> print up

Looks like a terribly bad design to me.


>> This should complain that "up" is not defined during the "print" call,
>> but not when move() is called. And of course there should be as little
>> magic as possible.
>>
>> Any way to achieve this?
> 
> >>> def move( direction ):
> ...   print( "move " + str( direction ) )
> ...
> >>> move( "up" )
> move up
> >>>
> >>> class using_directions:
> ... up = 42
> ... move( up )
> ...
> move 42
> >>> up
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'up' is not defined
> >>> _
> 
> Of course it's an abuse of the language. :-)

And, of course, it's totally useless as the move() function doesn't know
about the 'up' thing in the first place.

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


Re: Symbols as parameters?

2010-01-21 Thread Stefan Behnel
Alf P. Steinbach, 21.01.2010 11:38:
> * Carl Banks:
>> On Jan 20, 11:43 pm, Martin Drautzburg 
> [snip]
>>
>>> What I am really looking for is a way
>>>
>>> - to be able to call move(up)
>>> - having the "up" symbol only in the context of the function
>>> call
>>
>> Short answer is, you can't do it.
>>
> 
> On the contrary, it's not difficult to do.
> 
> I provided an example in my answer to the OP (first reply in the thread).

Erm, no, you didn't. You showed a) how to pass a string constant into a
function and b) how to pass a value from a bound variable. None of that is
helpful to the OP's problem.

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


Re: covert number into string

2010-01-21 Thread Jan Ulrich Hasecke
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 21.01.10 12:18, anusha k wrote:
> Hi,
> 
> Can anyone tell me how to convert number to words
> For example:
> If number = then it should give me *Nine thousand nine hundred
> ninetynine*
> Is there any build-in function or something that can do this for me
> Thank you in advance
> Anusha Kadambala
> 

Hey thats like an exercise in the wonderful German book "Python for Kids".

Should be pretty easy to implement it by yourself.

Maybe you can understand the code without the german comments.

But keep in mind that this is an excercise for kids in chapter 5. I am
sure there are better implementations.

# Python für Kids -- 3. Auflage, Kapitel 5
# Autor: Gregor Lingl
# Datum: 01. 03. 2004
# Loesung von Kapitel 5, Aufgabe 3:

def zahlwort(zahl):
einer = zahl % 10  # Einerstelle: Rest bei der Division von zahl
durch 10
if einer == 1: e = "ein"
elif einer == 2: e = "zwei"
elif einer == 3: e = "drei"
elif einer == 4: e = "vier"
elif einer == 5: e = "fünf"
elif einer == 6: e = "sechs"
elif einer == 7: e = "sieben"
elif einer == 8: e = "acht"
elif einer == 9: e = "neun"

zehner = zahl // 10  # Zehnerstelle: Ergebnis der Ganzzahldivision
 # von zahl durch 10
if zehner == 0:   z = ""
elif zehner == 1: z = "zehn"
elif zehner == 2: z = "zwanzig"
elif zehner == 3: z = "dreissig"
elif zehner == 4: z = "vierzig"
elif zehner == 5: z = "fünfzig"
elif zehner == 6: z = "sechzig"
elif zehner == 7: z = "siebzig"
elif zehner == 8: z = "achtzig"
elif zehner == 9: z ="neunzig"

if zahl == 11:print "elf"
elif zahl == 12:  print "zwölf"
elif zahl == 17:  print "siebzehn"
elif einer == 0:  print z
elif zehner == 1: print e+z
else: print e+"und"+z

zahl = raw_input("Gib eine zweistellige ganze Zahl ein: ")
zahl = int(zahl)  # macht aus dem String zahl eine ganze Zahl
zahlwort(zahl)
print

Cheers!
juh
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.10 (Darwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAktYPwwACgkQPUzUEFbILMRLWwCgjugY7Wxzec7AH8Esz1hNIf8d
WgoAoKgFo59NoBVk0jGZsqe5slOc7P9W
=cP1x
-END PGP SIGNATURE-

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


Re: Symbols as parameters?

2010-01-21 Thread Alf P. Steinbach

* Stefan Behnel:

Alf P. Steinbach, 21.01.2010 09:30:

* Martin Drautzburg:

- to be able to call move(up)
- having the "up" symbol only in the context of the function call

So it should look something like this

... magic, magic ...
move(up)
... unmagic, unmagic ...
print up


Looks like a terribly bad design to me.


That it is, in Python.



This should complain that "up" is not defined during the "print" call,
but not when move() is called. And of course there should be as little
magic as possible.

Any way to achieve this?

def move( direction ):

...   print( "move " + str( direction ) )
...

move( "up" )

move up

class using_directions:

... up = 42
... move( up )
...
move 42

up

Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'up' is not defined

_

Of course it's an abuse of the language. :-)


And, of course, it's totally useless as the move() function doesn't know
about the 'up' thing in the first place.


Hm, it seems as if you thought that the example was *literally* what the OP 
should do.


It was not: it just demonstrated the possibility.

Consider replacing the assignment with whatever, or alternatively, consider that 
perhaps 42 is indeed the value of "up" that the move() function knows about.



Cheers & hth.,

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


Re: Symbols as parameters?

2010-01-21 Thread Alf P. Steinbach

* Stefan Behnel:

Alf P. Steinbach, 21.01.2010 11:38:

* Carl Banks:

On Jan 20, 11:43 pm, Martin Drautzburg 

[snip]

What I am really looking for is a way

- to be able to call move(up)
- having the "up" symbol only in the context of the function
call

Short answer is, you can't do it.


On the contrary, it's not difficult to do.

I provided an example in my answer to the OP (first reply in the thread).


Erm, no, you didn't. You showed a) how to pass a string constant into a
function and b) how to pass a value from a bound variable. None of that is
helpful to the OP's problem.


Perhaps look again at that example. It demonstrates exactly what the OP asks 
for.


Cheers & hth.,

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


multiprocessing as batch system

2010-01-21 Thread Neal Becker
I'm using multiprocessing as a poor man's batch system.  It is working OK, 
except that it doesn't seem to do load balancing quite right.

I have a 8-cpu machine.  If I start, using multiprocessing pool, calling map 
with more than 8 elements, it will start 8 processes.  It seems, though, 
that when some of them finish, it does not start others right away.  The 
load average may be a lot less than 8 but still additional processes are not 
active.

Is there a way to use multiprocessing to achieve the effect I want?  (I 
really want a simple batch system, but without complex setup) 

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


Re: covert number into string

2010-01-21 Thread Joel Goldstick



anusha k wrote:

Hi,

Can anyone tell me how to convert number to words
For example:
If number = then it should give me *Nine thousand nine hundred
ninetynine*
Is there any build-in function or something that can do this for me
Thank you in advance
Anusha Kadambala




This might help:
http://snippets.dzone.com/posts/show/704
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess troubles

2010-01-21 Thread Tomas Pelka

On 01/21/2010 11:39 AM, Javier Collado wrote:

Hello,

If you set shell=False, then I think that arg2 should be separated
into two different parts.

Also, arg3 could be set just to pattern (no need to add extra spaces
or using str function).

Best regards,
 Javier

2010/1/21 Tomas Pelka:


Hey all,

have a problem with following piece of code:

--
import subprocess

paattern = "python"
cmd = "/usr/bin/locate"
arg1 = " -i"
arg2 = " -d /var/www/books/mlocate.db"
arg3 = str(" " + pattern)

p1 = subprocess.Popen([cmd, arg1, arg2, arg3], shell=False,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdoutdata, stderrdata) = p1.communicate()

print p1.returncode
print "%s -- %s" % (stdoutdata, stderrdata)
--

But return code is always 1 and command do not return any result/error
(stdoutdata, stderrdata are None). If I run this command (/usr/bin/locate -i
-d /var/www/books/mlocate.db python) from standard shell everything goes
fine.

Could you please give me an advice what I'm doing wrong?

Thanks
Cheers

--
Tom

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




Thanks Javier for advice, but sill same result. I'm running this code as 
cgi  script from apache. Weird is that when i run  it from shell as 
apache user, like



# su -s /bin/bash -c "/usr/bin/locate -i -d /var/www/books/mlocate.db 
python; echo $?" apache

0
---
I always get "0", but as cgi it returns "1". When I run this script by 
other user (tom), I'll obtain nonzero output what is OK.


Additional info:
#  su -s /bin/bash -c "ls -l /var/www/books/mlocate.db" apache
-rw-rw-r-- 1 tom books 1465653 Jan 20 13:33 /var/www/books/mlocate.db
so db is readable by apache

Whore source attached.

--
Tom


#!/usr/bin/python

import cgi
import cgitb; cgitb.enable()  # for troubleshooting
import subprocess
import sys
import os
sys.stderr = sys.stdout

command = ""
result = ""
stdoutdata = ""
stderrdata = ""

# Create instance of FieldStorage
form = cgi.FieldStorage()

# Get data from field 'pattern'
pattern = form.getvalue('pattern', 'None')
# Get data from field 're'
re = form.getvalue('re')

cmd = "/usr/bin/locate"
arg1 = "-i"
arg2a = "-d"
arg2b = "/var/www/books/mlocate.db"
arg3 = "-r"
arg4 = str(pattern)
p1 = None

if re == "re":
p1 = subprocess.Popen([cmd, arg1, arg2a, arg2b, arg3, arg4], 
shell=False, \
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
command = "%s %s %s %s %s %s" % (cmd, arg1, arg2a, arg2b, arg3, arg4)
else:
p1 = subprocess.Popen([cmd, arg1, arg2a, arg2b, arg4], shell=False, \
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
command = "%s %s %s %s %s " % (cmd, arg1, arg2a, arg2b, arg4)

(stdoutdata, stderrdata) = p1.communicate()

print "Content-type: text/html"
print

# debug
print "UID: %i " % os.getuid()
print "Search pattern: %s " % pattern
print """stdout: %s 
stderr: %s 
""" % (stdoutdata, stderrdata)
print "Return code: %i" % p1.returncode

print """

Hledej v books


Hledany vyraz:



Hledat pomoci regularniho vyrazu?






"""
if p1.returncode == 0:
if stdoutdata:
result = stdoutdata
else:
result = "Nic takoveho sem nenasel :/"

else:
result = 'Chyba: \
index souboru je bud zastaraly nebo doslo \
k chybe pri vyhledavani.%s \
%s' % (command, stderrdata)

print """
Hledany vyraz "%s" se nachazi v nasledujicich adresarich
%s
 
""" % (pattern, result)


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


ReportLab PDF Toolkit v2.4 released

2010-01-21 Thread Tim
We're pleased to announce the latest version of the ReportLab open
source PDF toolkit, now available for download here:

https://www.reportlab.com/software/opensource/rl-toolkit/download/

The ReportLab Toolkit is a library for programatically creating
documents in PDF format.  It's free, open-source software written in
Python, and released under a BSD type license.

Thanks,
-The ReportLab Team

https://www.reportlab.com/software/opensource/rl-toolkit/
download/">ReportLab Toolkit v2.4 -  The Open Source Library for
creating PDF Documents.  (21-Jan-2010)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: substitution

2010-01-21 Thread Wilbert Berendsen
Op maandag 18 januari 2010 schreef Adi:
> keys = [(len(key), key) for key in mapping.keys()]
> keys.sort(reverse=True)
> keys = [key for (_, key) in keys]
> 
> pattern = "(%s)" % "|".join(keys)
> repl = lambda x : mapping[x.group(1)]
> s = "fooxxxbazyyyquuux"
> 
> re.subn(pattern, repl, s)

I managed to make it even shorted, using the key argument for sorted, not 
putting the whole regexp inside parentheses and pre-compiling the regular 
expression:

import re

mapping = {
"foo" : "bar",
"baz" : "quux",
"quuux" : "foo"
}

# sort the keys, longest first, so 'aa' gets matched before 'a', because
# in Python regexps the first match (going from left to right) in a
# |-separated group is taken
keys = sorted(mapping.keys(), key=len)

rx = re.compile("|".join(keys))
repl = lambda x: mapping[x.group()]
s = "fooxxxbazyyyquuux"
rx.sub(repl, s)

One thing remaining: if the replacement keys could contain non-alphanumeric 
characters, they should be escaped using re.escape:

rx = re.compile("|".join(re.escape(key) for key in keys))


Met vriendelijke groet,
Wilbert Berendsen

-- 
http://www.wilbertberendsen.nl/
"You must be the change you wish to see in the world."
-- Mahatma Gandhi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Create object name from string value?

2010-01-21 Thread Gnarlodious
On Jan 20, 10:35 pm, Steven D'Aprano wrote:

> That's the wrong way to handle the problem. Named objects are only useful
> if you know the name of the object when writing the code. Otherwise, how
> do you know what name to use in the code?

Thank you for the help. I am gathering the names of all *.plist files
in a folder, creating objects named the filename, and accessing the
data like this:

Data.Server.Config.BaseURL
> http://Spectrumology.com/

Adding a .plist file would automatically create a plist dictionary
object inside the Data module.

> The right way to solve this problem is with a dictionary:
>
> for name in ["object1", "object2", "object3"]:
>     d = {name: classname()}
>     print d[name]

This works! However I end up saying:

d['Server'].Config.BaseURL

to get the data, when I should be saying:

Server.Config.BaseURL

> but for the record, the way to use exec is like this:
>
> exec("object1 = classname()")

I failed to make that work. So back to the original question. How to
make an instance named according to a string inside a variable? I
guess it should be in the top-level namespace, not inside a list or
dictionary.

-- Gnarlie
http://Gnarlodious.com/Gnarlodious
-- 
http://mail.python.org/mailman/listinfo/python-list


SIP v4.10 Released (Python Bindings Generator)

2010-01-21 Thread Phil Thompson
SIP v4.10 has been released and can be downloaded from
http://www.riverbankcomputing.com/software/sip/.

SIP is a tool for generating Python modules that wrap C or C++ libraries.
It is similar to SWIG.  It is used to generate PyQt and PyKDE.

The SIP license is similar to the Python License and is also licensed under
the GPL v2 and v3.

SIP runs on Windows, UNIX, Linux and MacOS/X.

SIP requires Python v2.3 or later and fully supports Python v3.

This release adds support for keyword arguments and docstrings.  Docstrings
may be either explictly specified or automatically generated.
Automatically generated docstrings describe the Python signatures of all
available overloads for a callable.  A significantly improved error
reporting mechanism uses those docstrings in exceptions raised when
arguments with incorrect types are passed.

Other features of SIP include:

- extension modules are implemented as a single binary .pyd or .so file (no
  Python stubs)
- support for Python new-style classes
- the ability to specify the super-type and meta-type used to wrap
  instances
- generated modules are quick to import, even for large libraries
- thread support
- the ability to re-implement C++ abstract and virtual methods in Python
- the ability to define Python classes that derive from abstract C++
  classes
- the ability to spread a class hierarchy across multiple Python modules
- the ability to wrap a C++ class in different ways and allow an
  application to select a particular implementation at run-time
- support for C++ namespaces
- support for C++ exceptions
- support for C++ operators
- an extensible build system written in Python that supports over 50
  platform/compiler combinations
- the generation of API files for IDEs that support autocompletion and call
  tips.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: substitution

2010-01-21 Thread MRAB

Wilbert Berendsen wrote:

Op maandag 18 januari 2010 schreef Adi:

keys = [(len(key), key) for key in mapping.keys()]
keys.sort(reverse=True)
keys = [key for (_, key) in keys]

pattern = "(%s)" % "|".join(keys)
repl = lambda x : mapping[x.group(1)]
s = "fooxxxbazyyyquuux"

re.subn(pattern, repl, s)


I managed to make it even shorted, using the key argument for sorted, not 
putting the whole regexp inside parentheses and pre-compiling the regular 
expression:


import re

mapping = {
"foo" : "bar",
"baz" : "quux",
"quuux" : "foo"
}

# sort the keys, longest first, so 'aa' gets matched before 'a', because
# in Python regexps the first match (going from left to right) in a
# |-separated group is taken
keys = sorted(mapping.keys(), key=len)


For longest first you need:

keys = sorted(mapping.keys(), key=len, reverse=True)


rx = re.compile("|".join(keys))
repl = lambda x: mapping[x.group()]
s = "fooxxxbazyyyquuux"
rx.sub(repl, s)

One thing remaining: if the replacement keys could contain non-alphanumeric 
characters, they should be escaped using re.escape:



Strictly speaking, not all non-alphanumeric characters, but only the
special ones.


rx = re.compile("|".join(re.escape(key) for key in keys))



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


Re: Sorted dictionary

2010-01-21 Thread Daniel Stutzbach
On Thu, Jan 21, 2010 at 2:27 AM, Raymond Hettinger  wrote:

> Using an underlying list to track sorted items
> means that insertion and deletion take O(n) time.
> That could be reduced to O(log n) time by using
> a blist or skiplist as the underlying structure
> for maintaining a sort.
>

Indeed.  In fact, blist 1.1 (to be released within a month or so) will
include sorteddict, sortedset, sortedlist, weaksortedset, and weaksortedlist
types.

--
Daniel Stutzbach, Ph.D.
President, Stutzbach Enterprises, LLC 
-- 
http://mail.python.org/mailman/listinfo/python-list


creating a python program to control the cursor and click a location on the screen at specified delay interval?

2010-01-21 Thread John Haggerty
HiSo just testing the feasibility of doing this but I was interested in
creating a primitive way of scripting gui applications w/o using a remote
network client by having the application up and then almost just using the
pointer position to figure out where it is and then click it and any
subsequent dialogs. I would have to assume that someone has done something
like this.

In principle this could be done I don't know if this is possible to
implement in python cross platform but the system I am using is just your
standard Ubuntu Linux 9.10 system.

Would be interesting to see something already in existance however to avoid
duplication of work.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Create object name from string value?

2010-01-21 Thread Alf P. Steinbach

* Gnarlodious:

On Jan 20, 10:35 pm, Steven D'Aprano wrote:


That's the wrong way to handle the problem. Named objects are only useful
if you know the name of the object when writing the code. Otherwise, how
do you know what name to use in the code?


Thank you for the help. I am gathering the names of all *.plist files
in a folder, creating objects named the filename, and accessing the
data like this:

Data.Server.Config.BaseURL

http://Spectrumology.com/


Adding a .plist file would automatically create a plist dictionary
object inside the Data module.


The right way to solve this problem is with a dictionary:

for name in ["object1", "object2", "object3"]:
d = {name: classname()}
print d[name]


This works! However I end up saying:

d['Server'].Config.BaseURL

to get the data, when I should be saying:

Server.Config.BaseURL


but for the record, the way to use exec is like this:

exec("object1 = classname()")


I failed to make that work. So back to the original question. How to
make an instance named according to a string inside a variable? I
guess it should be in the top-level namespace, not inside a list or
dictionary.


I don't understand how you intend to use a variable whose name comes from 
dynamic data.


So I agree with Steven that it's the wrong way to handle the problem  -- 
whatever the problem is!


But, if it can help:


  >>> import __main__
  >>> setattr( __main__, "blah", 123 )
  >>> blah
  123
  >>> _


Cheers,

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


PyQt v4.7 Released

2010-01-21 Thread Phil Thompson
PyQt v4.7 has been released and is available from
http://www.riverbankcomputing.com/software/pyqt/.

PyQt is a comprehensive set of bindings for the Qt application and UI
framework from Nokia.  It supports the same platforms as Qt (Windows,
Linux and MacOS/X).

PyQt supports Python v3 and Python v2.3 and later.

The highlights of this release include:

 - full support for Qt v4.6.1 including the new animation and state machine
   frameworks, gesture and multi-touch support, and advanced graphics
   effects (blurring, colourising, drop shadows)

 - all callables have docstrings that describe the Python signatures of all
   available overloads

 - keyword arguments are supported for all optional arguments.

Windows installers are provided for the GPL version of PyQt which contains
everything needed for PyQt development (including Qt, Qt Designer,
QScintilla, and MySQL, PostgreSQL, SQLite and ODBC drivers) except Python
itself.

PyQt v4 is implemented as a set of 19 extension modules containing over
400 classes and over 6,000 functions and methods.

QtCore
The non-GUI infrastructure including event loops, threads, i18n,
Unicode, signals and slots, user and application settings, mapped
files and shared memory.

QtDesigner
A set of classes that allow the Qt Designer GUI design tool to be
extended with PyQt.

QtGui
A rich collection of GUI widgets.

QtHelp
A set of classes for creating and viewing searchable documentation and
being able to integrate online help with PyQt applications.  It
includes the C++ port of the Lucene text search engine.

QtNetwork
A set of classes to support TCP and UDP socket programming and higher
level protocols (eg. HTTP, SSL).

QtOpenGL
A set of classes that allows PyOpenGL to render onto Qt widgets.

QtScript
A set of classes that implements a JavaScript interpreter.  Python
objects may be exposed in the interpreter as JavaScript objects.

QtScriptTools
A debugger for the JavaScript interpreter.

QtSql
A set of classes that implement SQL data models and interfaces to
industry standard databases.  The Windows installers include support
for SQLite, MySQL, PostgreSQL and ODBC.

QtSvg
A set of classes to render SVG files onto Qt widgets.

QtTest
A set of classes to automate unit testing of PyQt applications and
GUIs.

QtWebKit
This implements a web browser engine based on the WebKit engine used by
Apple's Safari browser.  It allows the methods and properties of Python
objects to be published and appear as JavaScript objects to scripts
embedded in HTML pages.

QtXML
A set of classes that implement DOM and SAX parsers.

QtXMLPatterns
A set of classes that implement XQuery and XPath support for XML and
custom data models.

QtAssistant
A set of classes that enables the Qt Assistant online help browser to
be integrated with an application.

QAxContainer
A set of classes for Windows that allows the integration of ActiveX
controls and COM objects.

phonon
A cross-platform multimedia framework that enables the use of audio and
video content in PyQt applications.  DirectX is used as the Windows
backend, QuickTime as the MacOS/X backend, and GStreamer as the Linux
backend.

QtMultimedia
A set of classes that provide low-level multimedia functions.
Application developers would normally use the phonon module.

DBus
PyQt includes dbus.mainloop.qt that allows the Qt event loop to be used
with the standard DBus Python bindings.

PyQt includes the pyuic4 utility which generates Python code to implement
user interfaces created with Qt Designer in the same way that the uic
utility generates C++ code.  It is also able to load Designer XML files
dynamically.

PyQt is available under the GPL and a commercial license.  Unlike Qt, PyQt
is not available under the LGPL.  The commercial PyQt license allows GPL
applications to be relicensed at any time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: substitution

2010-01-21 Thread Iain King
On Jan 21, 2:18 pm, Wilbert Berendsen  wrote:
> Op maandag 18 januari 2010 schreef Adi:
>
> > keys = [(len(key), key) for key in mapping.keys()]
> > keys.sort(reverse=True)
> > keys = [key for (_, key) in keys]
>
> > pattern = "(%s)" % "|".join(keys)
> > repl = lambda x : mapping[x.group(1)]
> > s = "fooxxxbazyyyquuux"
>
> > re.subn(pattern, repl, s)
>
> I managed to make it even shorted, using the key argument for sorted, not
> putting the whole regexp inside parentheses and pre-compiling the regular
> expression:
>
> import re
>
> mapping = {
>         "foo" : "bar",
>         "baz" : "quux",
>         "quuux" : "foo"
>
> }
>
> # sort the keys, longest first, so 'aa' gets matched before 'a', because
> # in Python regexps the first match (going from left to right) in a
> # |-separated group is taken
> keys = sorted(mapping.keys(), key=len)
>
> rx = re.compile("|".join(keys))
> repl = lambda x: mapping[x.group()]
> s = "fooxxxbazyyyquuux"
> rx.sub(repl, s)
>
> One thing remaining: if the replacement keys could contain non-alphanumeric
> characters, they should be escaped using re.escape:
>
> rx = re.compile("|".join(re.escape(key) for key in keys))
>
> Met vriendelijke groet,
> Wilbert Berendsen
>
> --http://www.wilbertberendsen.nl/
> "You must be the change you wish to see in the world."
>         -- Mahatma Gandhi

Sorting it isn't the right solution: easier to hold the subs as tuple
pairs and by doing so let the user specify order.  Think of the
following subs:

"fooxx" -> "baz"
"oxxx" -> "bar"

does the user want "bazxbazyyyquuux" or "fobarbazyyyquuux"?

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


Re: substitution

2010-01-21 Thread Wilbert Berendsen
Op donderdag 21 januari 2010 schreef MRAB:

> For longest first you need:
> 
>  keys = sorted(mapping.keys(), key=len, reverse=True)

Oh yes, I cut/pasted the wrong line :-)
Just for clarity:

import re

mapping = {
"foo" : "bar",
"baz" : "quux",
"quuux" : "foo"
}

# sort the keys, longest first, so 'aa' gets matched before 'a', because
# in Python regexps the first match (going from left to right) in a
# |-separated group is taken
keys = sorted(mapping.keys(), key=len, reverse=True)

rx = re.compile("|".join(keys))
repl = lambda x: mapping[x.group()]
s = "fooxxxbazyyyquuux"
rx.sub(repl, s)

>> One thing remaining: if the replacement keys could contain non-alphanumeric 
>> characters, they should be escaped using re.escape:
>> rx = re.compile("|".join(re.escape(key) for key in keys))
>> 
>Strictly speaking, not all non-alphanumeric characters, but only the
>special ones.

True, although the re.escape function simply escapes all non-alphanumeric 
characters :)

And here is a factory function that returns a translator given a mapping. The 
translator can be called to perform replacements in a string:

import re

def translator(mapping):
keys = sorted(mapping.keys(), key=len, reverse=True)
rx = re.compile("|".join(keys))
repl = lambda m: mapping[m.group()]
return lambda s: rx.sub(repl, s)

#Usage:
>>> t = translator(mapping)
>>> t('fooxxxbazyyyquuux')
'barxxxquuxyyyfoo'


w best regards,
Wilbert Berendsen

-- 
http://www.wilbertberendsen.nl/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Create object name from string value?

2010-01-21 Thread Tim Chase

Gnarlodious wrote:

for name in ["object1", "object2", "object3"]:
d = {name: classname()}
print d[name]


This works! However I end up saying:

d['Server'].Config.BaseURL

to get the data, when I should be saying:

Server.Config.BaseURL


It sounds like you want a mapping of strings to class objects 
(not instances), so you can do something like


  mapping = {
"object1": object1,
"object2": some_module.object2,
"object3": other_module.namespace.object3,
}

  MyClass = mapping["object1"]
  server = MyClass(initialization_params)
  # the above two lines can be written as
  # server = mapping["object1"](init_params)
  print server.Config.BaseURL


-tkc





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


distutils not finding all of my pure python modules

2010-01-21 Thread Jeremy
I have a small set of Python packages/modules that I am putting
together.  I'm having trouble in that when I run

python setup.py sdist

I don't get all of my pure python modules.  The setup.py script I use
is:

# =
from distutils.core import setup

purePythonModules = ['regex', 'gnuFile']

setup(name='PythonForSafeguards',
version='0.9.1',
description = 'Python code for MCNP and Safeguards analysis.',
author = 'Jake the Snake',
author_email = 'someth...@blah.com',
packages = ['MCNP', 'Safeguards'],
url='http://lanl.gov',
py_modules = purePythonModules,
)

# =

Everythin seems to work fine except the gnuFile.py script does not get
put into the distribution.  I know the file exists in the same
directory as regex.py and has the same permissions.

Does anyone know what is going on here?  I'm using Python 2.6.4.

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


Re: Symbols as parameters?

2010-01-21 Thread Dave Angel

Martin Drautzburg wrote:

Hello all,

When passing parameters to a function, you sometimes need a paramter
which can only assume certain values, e.g.

def move (direction):
...
If direction can only be "up", "down", "left" or "right", you can solve
this by passing strings, but this is not quite to the point:

- you could pass invalid strings easily
- you need to quote thigs, which is a nuisance
- the parameter IS REALLY NOT A STRING, but a direction

Alternatively you could export such symbols, so when you "import *" you
have them available in the caller's namespace. But that forces you
to "import *" which pollutes your namespace.

What I am really looking for is a way

- to be able to call move(up)
- having the "up" symbol only in the context of the function call

So it should look something like this

... magic, magic ...
move(up)
... unmagic, unmagic ...
print up

This should complain that "up" is not defined during the "print" call,
but not when move() is called. And of course there should be as little
magic as possible.

Any way to achieve this?


  
My favorite answer provided by others was adding the attributes to the 
function right after the function definition, then using

 move(move.up)

But another approach is to define the function as:

def move(up=False, down=False, right=False, left=False):
   if up:
 ...
  if down:
  

and call it as:

move(up=True)

DaveA

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


Re: Create object name from string value?

2010-01-21 Thread Adam Tauno Williams
> > but for the record, the way to use exec is like this:
> > exec("object1 = classname()")
> I failed to make that work. So back to the original question. How to
> make an instance named according to a string inside a variable? I
> guess it should be in the top-level namespace, not inside a list or
> dictionary.

I think what you want is more like:

classclass = eval(classname)
x = classclass(...args...)



-- 
OpenGroupware developer: awill...@whitemice.org

OpenGroupare & Cyrus IMAPd documenation @


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


Re: multiprocessing as batch system

2010-01-21 Thread Adam Tauno Williams
On Thu, 2010-01-21 at 07:13 -0500, Neal Becker wrote:
> I'm using multiprocessing as a poor man's batch system.  It is working OK, 
> except that it doesn't seem to do load balancing quite right.
> I have a 8-cpu machine.  If I start, using multiprocessing pool, calling map 
> with more than 8 elements, it will start 8 processes.  It seems, though, 
> that when some of them finish, it does not start others right away.  The 
> load average may be a lot less than 8 but still additional processes are not 
> active.

If your processes are I/O bound your system will never appear to be
saturated.  Multiple pending processes and a low load average usually
indicated waiting on some other resource.

> Is there a way to use multiprocessing to achieve the effect I want?  (I 
> really want a simple batch system, but without complex setup) 

Well, honestly, that isn't possible (unless you just choose to ignore
all the things that can go wrong: crashed worked, hung workers, etc...)

-- 
OpenGroupware developer: awill...@whitemice.org

OpenGroupare & Cyrus IMAPd documenation @


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


Re: Create object name from string value?

2010-01-21 Thread Dave Angel

Gnarlodious wrote:

On Jan 20, 10:35 pm, Steven D'Aprano wrote:

  

That's the wrong way to handle the problem. Named objects are only useful
if you know the name of the object when writing the code. Otherwise, how
do you know what name to use in the code?



Thank you for the help. I am gathering the names of all *.plist files
in a folder, creating objects named the filename, and accessing the
data like this:

Data.Server.Config.BaseURL
  

http://Spectrumology.com/



Adding a .plist file would automatically create a plist dictionary
object inside the Data module.

  

The right way to solve this problem is with a dictionary:

for name in ["object1", "object2", "object3"]:
d =name: classname()}
print d[name]



This works! However I end up saying:

d['Server'].Config.BaseURL

to get the data, when I should be saying:

Server.Config.BaseURL

  

but for the record, the way to use exec is like this:

exec("object1 =lassname()")



I failed to make that work. So back to the original question. How to
make an instance named according to a string inside a variable? I
guess it should be in the top-level namespace, not inside a list or
dictionary.

-- Gnarlie
http://Gnarlodious.com/Gnarlodious

  
I know you figure you have a specific list of files, and that they'll 
never conflict with the other global variables you've defined.  But 
adding globals dynamically is "magic", and can lead to very obscure 
bugs.  Suppose sometime in the future somebody adds another plist file 
with the same name as one of your functions?


Put it inside a dummy class, as follows:

>>> class Plist: pass
...
>>> plists = Plist()
>>> setattr(plists, "Server", 42)
>>> plists.Server
42
>>>

That avoids the ["Server"] syntax, but still doesn't risk polluting your 
global namespace with arbitrary names.  And in the example above, you'd 
be using

  plists.Server.Config.BaseURL


And if you must use the global namespace, you can simply do:

>>> globals()["Server"] = 42
>>> Server
42

DaveA

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


simple pub/sub

2010-01-21 Thread Steve Howell
Hi, I'm looking for ideas on building a simple architecture that
allows a bunch of independent Python processes to exchange data using
files and perform calculations.

One Python program would be collecting data from boat instruments on a
serial port, then writing that info out to a file, and also
transmitting data to instruments as needed (again through the serial
port).  It would be the most complex program in terms of having to
poll file descriptors, or something similar, but I want to limit its
job to pure communication handling.

Then, I would have a bunch of programs doing various calculations on
the input stream.  It's totally acceptable if they just sleep a bit,
wake up, see if there is any new data, and if so, do some
calculations, so I will probably just use this:

http://www.dabeaz.com/generators/follow.py

Some of the "calculator" programs might be looking for trends in the
data, and when a certain threshold is reached, they will need to
notify the comm program of the new message.  To avoid collisions
between all the different calculator programs, I am thinking the
simplest thing is just have them each write to their own output file.

So then the comm program has multiple data sources.  It wants to track
to the serial port, but it also wants to monitor the output files from
the various calculator processes.  I want to do this in a mostly
nonblocking way, so I would probably poll on the file descriptors.

The only problems are that select "...cannot be used on regular files
to determine whether a file has grown since it was last read," and it
only works on Unix for files.  (I'm using Unix myself, but one of the
other programmers insists on Windows, and is resisting Python as
well.)

So a variation would be that the calculator programs talk to the comm
program via sockets, which seems slightly on the heavy side, but it is
certainly feasible.

I know that something like twisted could probably solve my problem,
but I'm also wondering if there is some solution that is a little more
lightweight and batteries-included.

At the heart of the matter, I just want the programs to be able to do
the following tasks.

  1) All programs will occasionally need to write a line of text to
some data stream without having to lock it.  (I don't care if the
write blocks.)
  2) All programs will need to be able to do a non-blocking read of a
line of text from a data stream.  (And there may be multiple
consumers.)
  3) The comm program will need to be able to poll the serial port and
input data streams to see which ones are ready.

Any thoughts?




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


Re: Create object name from string value?

2010-01-21 Thread Stephen Hansen
On Thu, Jan 21, 2010 at 6:23 AM, Gnarlodious  wrote:

> This works! However I end up saying:
>
> d['Server'].Config.BaseURL
>
> to get the data, when I should be saying:
>
> Server.Config.BaseURL


That's the thing: you should not actually be saying that.

d['Server'].Config.BaseURL is precisely what you should be saying.

You need to adjust your expectations to the language you are using and how
it operates. Whatever aesthetic sense in you that is objecting to using a
dictionary is something you just need to get past. If you don't like the
dictionary getitem syntax, you can always do:

>>> class AttrDict(dict):
... def __getattr__(self, key):
... return self[key]
...
>>> a = AttrDict()
>>> a["test"] = 1
>>> a.test
1

Is there any real reason you can't write Servers["Server"].Config.BaseURL or
Servers.Server.Config.BaseURL, or is it just an itch that's bugging you? If
its the latter, then it's better to just not scratch it and it'll go away
when you get more used to the language :)

Its not easy to do what you're asking for. People ask for it every once in
awhile. But it's just not the Pythonic way to approach the problem, and
while there are things you can do to accomplish it, they're hacks and are
not guaranteed to work consistently. Its not even a oversight in Python,
something the devs never considered: its intentionally designed to be this
way.

How come a dictionary (or class as above) isn't good enough?

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


Re: simple pub/sub

2010-01-21 Thread Adam Tauno Williams
On Thu, 2010-01-21 at 08:54 -0800, Steve Howell wrote:
> Hi, I'm looking for ideas on building a simple architecture that
> allows a bunch of independent Python processes to exchange data using
> files and perform calculations.
> One Python program would be collecting data from boat instruments on a
> serial port, then writing that info out to a file, and also
> transmitting data to instruments as needed (again through the serial
> port).  It would be the most complex program in terms of having to
> poll file descriptors, or something similar, but I want to limit its
> job to pure communication handling.

This should be pretty easy using multiprocessing.  In OpenGroupware
Coils we have a master process

 that spins up children (workers, that each provide a distinct service) it 
opens a Pipe to each child to send messages to the child and a Queue from which 
it reads [all children (clients) write to the Queue and listen on their Pipe].  
Then the master just listens on its pipe and forwards messages from children to 
other children.

All children are Service objects
.
  Then implementing a new service [type of worker] is as easy as (our brutally 
simple pubsub service) 


Hope that helps.

-- 
OpenGroupware developer: awill...@whitemice.org

OpenGroupare & Cyrus IMAPd documenation @


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


Python sys.prefix

2010-01-21 Thread zachar
Hi All,

I need some help about my "problem":
I compiled and installed python with ./configure --prefix=/opt/pyhon2.6.4... 
But I have to move it to a different directory (the reason is very difficult 
but I must do this)... I started the interpreter from shell and I was surprised 
because It still worked and It changed the sys.prefix so it pointed to the 
correct place so the sys.path was correct The questions are: HOW? Is it a 
feature which is not documented (at least I couldn't find anything about it)?

From the official python documentation 
(http://docs.python.org/library/sys.html?highlight=sys#sys.prefix):
"sys.prefix¶

A string giving the site-specific directory prefix where the platform 
independent Python files are installed; by default, this is the string 
'/usr/local'. This can be set at build time with the --prefix argument to the 
configure script. The main collection of Python library modules is installed in 
the directory prefix + '/lib/pythonversion' while the platform independent 
header files (all except pyconfig.h) are stored in prefix + 
'/include/pythonversion', where version is equal to version[:3]."

In my case, this is not correct: it looks, after I call the interpreter, 
something change the sys.prefix variable and point it to the right place and 
not to that directory which I used with the configuration script... This is 
very useful (I am happy because it solves one of my problems) but I am afraid 
of it will be do it in a different way in the future (as it is not documented).

Thanks,
Regards,
Balazs
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simple pub/sub

2010-01-21 Thread Steve Howell
On Jan 21, 9:03 am, Adam Tauno Williams 
wrote:
> On Thu, 2010-01-21 at 08:54 -0800, Steve Howell wrote:
> > Hi, I'm looking for ideas on building a simple architecture that
> > allows a bunch of independent Python processes to exchange data using
> > files and perform calculations.
> > One Python program would be collecting data from boat instruments on a
> > serial port, then writing that info out to a file, and also
> > transmitting data to instruments as needed (again through the serial
> > port).  It would be the most complex program in terms of having to
> > poll file descriptors, or something similar, but I want to limit its
> > job to pure communication handling.
>
> This should be pretty easy using multiprocessing.  In OpenGroupware
> Coils we have a master process
>  
> that spins up children (workers, that each provide a distinct service) it 
> opens a Pipe to each child to send messages to the child and a Queue from 
> which it reads [all children (clients) write to the Queue and listen on their 
> Pipe].  Then the master just listens on its pipe and forwards messages from 
> children to other children.
>
> All children are Service objects
> .  
> Then implementing a new service [type of worker] is as easy as (our brutally 
> simple pubsub service) 
> 
>
> Hope that helps.
>

It does indeed!  I'm gonna try this approach for now.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simple pub/sub

2010-01-21 Thread Aahz
In article <0af0eff2-50e2-44aa-81f1-b3d12cb26...@a15g2000yqm.googlegroups.com>,
Steve Howell   wrote:
>
>Hi, I'm looking for ideas on building a simple architecture that
>allows a bunch of independent Python processes to exchange data using
>files and perform calculations.

SQLite?
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

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


Re: Symbols as parameters?

2010-01-21 Thread Carl Banks
On Jan 21, 2:38 am, "Alf P. Steinbach"  wrote:
> * Carl Banks:
>
> > On Jan 20, 11:43 pm, Martin Drautzburg 
> [snip]
>
> >> What I am really looking for is a way
>
> >>         - to be able to call move(up)
> >>         - having the "up" symbol only in the context of the function call
>
> > Short answer is, you can't do it.
>
> On the contrary, it's not difficult to do.
>
> I provided an example in my answer to the OP (first reply in the thread).

Your example doesn't remotely do what the OP was asking for.  In fact
your example is so preposterous I question your sanity.


> However, it's IMHO an abuse of the language, not something that one should do.

Usually people abuse the language to achieve something (ostensibly)
useful.  Your example is so useless I don't think I would even call it
abuse.

As best as I can tell, what it is is you attempting to make yourself
look like some kind of badass by answering some absurdly literal
interpretation of the OP's question.

Except you haven't even done that:

class using_directions:
up = 42
move( up )
print up # <- clearly not confined to context of function call



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


Closures in metaclasses

2010-01-21 Thread Falcolas
I'm running into an issue with closures in metaclasses - that is, if I
create a function with a closure in a metaclass, the closure appears
to be lost when I access the final class. I end up getting the text
'param' instead of the actual tags I am expecting:

ALL_TAGS =  ['a', 'abbr', 'acronym', 'address', 'applet', 'b', 'bdo',
'big'] #snip

def _tag_meta(name, bases, dict_):
for tag in ALL_TAGS:
def generic_tag(*args, **kwargs):
return Tag._generate_tag(tag, *args, **kwargs)
#generic_tag = eval("lambda *args, **kwargs: Tag._generate_tag
('%s', *args, **kwargs)" % tag)
dict_[tag] = staticmethod(generic_tag)
return type(name, bases, dict_)

class Tag(object):
__metaclass__ = _tag_meta
@staticmethod
def _generate_tag(tag_name, *args, **kwargs):
# Does the expected, following is just for the example's sake
return tag_name

Here's the output from my actual class:
$ python
Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from htmlgen import Tag
>>> Tag.html("foo")
'\nfoo\n'
>>>

Using the eval shown above works as expected, but I'd rather go with
the closures, if someone can help me figure out what's going on.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorted dictionary

2010-01-21 Thread Jan Kaliszewski

21-01-2010, 07:21:22 Dennis Lee Bieber  wrote:


How does this differ from all the other "ordered dictionary" schemes
out there (and maybe even included in 2.7? I'm still on 2.5)


It's completely different, please read first paragraph of page I linked  
(http://code.activestate.com/recipes/576998/).


Regards,
*j

--
Jan Kaliszewski (zuo) 
--
http://mail.python.org/mailman/listinfo/python-list


Re: installing psycopg2-2.0.13 with python3.1

2010-01-21 Thread Iain Barnett

On 21 Jan 2010, at 00:11, Gabriel Genellina wrote:

> En Wed, 20 Jan 2010 19:45:44 -0300, Iain Barnett  
> escribió:
> 
>> Would anyone know if it's possible to install psycopg2-2.0.13 with 
>> python3.1.1 (or similar)?I can install it with python2.6 with no problems, 
>> but obviously I'd prefer to use the latest version. My system is OSX10.6, 
>> and I'm new to Python.
> 
> If you're new to Python, perhaps it's better to stay with the 2.6 version.
> 
> Python 3.x introduced some incompatible changes in the language; not all 
> third-party packages are available for Python 3.x yet. Regarding psycopg2, 
> although some work has been done [1], there is no "official" release 
> compatible with Python 3 yet.
> 
> If you insist on using Python 3.1, there is another interface to PostgreSQL 
> called pg8000 that claims to be Python 3.x compatible (I've not actually 
> tested it).
> 
> [1] http://mail.python.org/pipermail/python-porting/2008-December/04.html
> [2] http://pybrary.net/pg8000/
> 
> -- 
> Gabriel Genellina
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

On 20 Jan 2010, at 23:58, Philip Semanchuk wrote:

> 
> On Jan 20, 2010, at 5:45 PM, Iain Barnett wrote:
> 
>> Hi,
>> 
>> Would anyone know if it's possible to install psycopg2-2.0.13 with 
>> python3.1.1 (or similar)? When I try I get the following
>> 
>> $ sudo python setup.py install
>> Password:
>> File "setup.py", line 233
>>   except Warning, w:
>> ^
>> SyntaxError: invalid syntax
>> 
>> 
>> I can install it with python2.6 with no problems, but obviously I'd prefer 
>> to use the latest version. My system is OSX10.6, and I'm new to Python.
> 
> Hi Iain,
> I've been out of the psycopg loop for a while now, but my guess is that the 
> answer to your question is no. There are some Python 3-related checkins in 
> the psycopg2 repository, but it looks like they're not ready for public use 
> yet (unless you're adventurous).
> 
> Here's the source repository, which contains a commit commented "First round 
> of changes for Python 3":
> https://dndg.it/cgi-bin/gitweb.cgi?p=public/psycopg2.git
> 
> If you scroll to the bottom of that page you'll see a "head" created 
> especially for Python 2 which is where 2.0.13 came from.
> 
> If you're willing to do some hacking on your own, Martin v. Löwis ported 
> psycopg2 to Python 3 and provided a diff:
> http://mail.python.org/pipermail/python-porting/2008-December/18.html
> 
> Last but not least, I should note that psycopg has its own mailing list, and 
> I bet they know more about it there:
> http://lists.initd.org/mailman/listinfo/psycopg
> 
> Hope this helps. Psycopg & Postgres both worked wonderfully well for me.
> 
> Cheers
> Philip
> -- 
> http://mail.python.org/mailman/listinfo/python-list

Thanks to both of you, it really is much appreciated.

Regards
Iain


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


Re: Closures in metaclasses

2010-01-21 Thread Arnaud Delobelle
Falcolas  writes:

> I'm running into an issue with closures in metaclasses - that is, if I
> create a function with a closure in a metaclass, the closure appears
> to be lost when I access the final class. I end up getting the text
> 'param' instead of the actual tags I am expecting:
>
> ALL_TAGS =  ['a', 'abbr', 'acronym', 'address', 'applet', 'b', 'bdo',
> 'big'] #snip
>
> def _tag_meta(name, bases, dict_):
> for tag in ALL_TAGS:
> def generic_tag(*args, **kwargs):
> return Tag._generate_tag(tag, *args, **kwargs)
> #generic_tag = eval("lambda *args, **kwargs: Tag._generate_tag
> ('%s', *args, **kwargs)" % tag)
> dict_[tag] = staticmethod(generic_tag)
> return type(name, bases, dict_)

This is almost a FAQ and has nothing to do with metaclasses.  The
simplest solution usually involves adding a default argument 'tag=tag'
to the function you define (here, generic_tag), but you can't do this
here because you have a **kwargs argument.  Instead, you can use a
closure and do this for example:

def factory(tag):
def generic_tag(*args, **kwargs):
return Tag._generate_tag(tag, *args, **kwargs)
return generic_tag

def _tag_meta(name, bases, dict_):
for tag in ALL_TAGS:
dict_[tag] = staticmethod(factory(tag))
return type(name, bases, dict_)

Then your Tag example class will work as you expect:

class Tag(object):
__metaclass__ = _tag_meta
@staticmethod
def _generate_tag(tag_name, *args, **kwargs):
# Does the expected, following is just for the example's sake
return tag_name

I am sure that there are plenty of discussions of this issue in the
archives of c.l.python.  I just can't think of a good keyword to google
it ATM.

However, I am usure about why you are using a metaclass.

HTH

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


Re: Closures in metaclasses

2010-01-21 Thread Falcolas
On Jan 21, 11:24 am, Arnaud Delobelle  wrote:
> Falcolas  writes:
> > I'm running into an issue with closures in metaclasses - that is, if I
> > create a function with a closure in a metaclass, the closure appears
> > to be lost when I access the final class. I end up getting the text
> > 'param' instead of the actual tags I am expecting:
>
> > ALL_TAGS =  ['a', 'abbr', 'acronym', 'address', 'applet', 'b', 'bdo',
> > 'big'] #snip
>
> > def _tag_meta(name, bases, dict_):
> >     for tag in ALL_TAGS:
> >         def generic_tag(*args, **kwargs):
> >             return Tag._generate_tag(tag, *args, **kwargs)
> >         #generic_tag = eval("lambda *args, **kwargs: Tag._generate_tag
> > ('%s', *args, **kwargs)" % tag)
> >         dict_[tag] = staticmethod(generic_tag)
> >     return type(name, bases, dict_)
>
> This is almost a FAQ and has nothing to do with metaclasses.  The
> simplest solution usually involves adding a default argument 'tag=tag'
> to the function you define (here, generic_tag), but you can't do this
> here because you have a **kwargs argument.  Instead, you can use a
> closure and do this for example:
>
> def factory(tag):
>     def generic_tag(*args, **kwargs):
>         return Tag._generate_tag(tag, *args, **kwargs)
>     return generic_tag
>
> def _tag_meta(name, bases, dict_):
>     for tag in ALL_TAGS:
>         dict_[tag] = staticmethod(factory(tag))
>     return type(name, bases, dict_)


I see - I was thinking it would preserve the closure from the for
statement, but I can see now why that would be wrong.

>
> However, I am usure about why you are using a metaclass.
>
> HTH
>
> --
> Arnaud

It was the easiest way I found to add a lot of static methods to the
Tag class without writing each one out. __getattr__ was not working
for this application. This is for a very simple application, and I
didn't want to add a lot of complexity to it's use. I'm always open
for other options OTOH.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorted dictionary

2010-01-21 Thread Jan Kaliszewski

Dnia 21-01-2010 o 08:49:22 Chris Rebert  napisał(a):


On Wed, Jan 20, 2010 at 5:50 PM, Steven D'Aprano
 wrote:

On Thu, 21 Jan 2010 02:02:02 +0100, Jan Kaliszewski wrote:



http://code.activestate.com/recipes/576998/



What's the advantage of that over sorting the keys as needed?


E.g.

for key in sorted(dict):
   print key


works.


Well, it does spread out the cost of sorting the key list over each of
the N distinct key assignments, versus sorting the entire list all at
once, on-demand at the end of the process. And you avoid having to
traverse the M buckets in the dictionary to locate the N keys in the
first place. So it has different performance characteristics, which
could theoretically matter depending on the use case; e.g. it could
avoid a GUI application hanging for several seconds while it sorts a
large list of keys.


Generally, I see 3 possible approaches:

1. What Steven wrote about: simply sort all keys when you need to get them  
sorted (it needs iteration over whole a dict).  In many cases it's good  
enough (so is the best, because of simplicity) -- e.g. when a dict is not  
very long (very common case), or when that sorting it is a rare operation.  
Sort always when a key is added/deleted, maintaining an auxiliary list of  
sorted keys (sufficient especially when you modify a dict rarely and get  
from it often).


2. Sort all keys on-demand -- but only if a dict is marked as "modified".  
Mark a dict as "modified" when you add/delete any key; and mark a dict as  
"unmodified" when sorting. (Of course, it can be automatized, see e.g.:  
http://pypi.python.org/pypi/sorteddict). Nice, if your use-pattern is:  
add/del a lot, *then* only get/iter a lot...


3. Continually (at each set/del of a key) maintain auxiliary sorted list  
of keys -- using binary search (as I did), heap queue (see:  
http://pypi.python.org/pypi/HeapDict) or such an algorithm. I think this  
approach is the best when you have quite long dict, and you add/del fairly  
often and get/iter very often.


Regards,
*j

--
Jan Kaliszewski (zuo) 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Symbols as parameters?

2010-01-21 Thread Diez B. Roggisch

Am 21.01.10 12:58, schrieb Alf P. Steinbach:

* Stefan Behnel:

Alf P. Steinbach, 21.01.2010 11:38:

* Carl Banks:

On Jan 20, 11:43 pm, Martin Drautzburg 

[snip]

What I am really looking for is a way

- to be able to call move(up)
- having the "up" symbol only in the context of the function
call

Short answer is, you can't do it.


On the contrary, it's not difficult to do.

I provided an example in my answer to the OP (first reply in the
thread).


Erm, no, you didn't. You showed a) how to pass a string constant into a
function and b) how to pass a value from a bound variable. None of
that is
helpful to the OP's problem.


Perhaps look again at that example. It demonstrates exactly what the OP
asks for.


Perhaps look again at the requirements:

"""
  - the parameter IS REALLY NOT A STRING, but a direction
"""

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


Re: Symbols as parameters?

2010-01-21 Thread Alf P. Steinbach

* Carl Banks:

On Jan 21, 2:38 am, "Alf P. Steinbach"  wrote:

* Carl Banks:


On Jan 20, 11:43 pm, Martin Drautzburg 

[snip]


What I am really looking for is a way
- to be able to call move(up)
- having the "up" symbol only in the context of the function call

Short answer is, you can't do it.

On the contrary, it's not difficult to do.

I provided an example in my answer to the OP (first reply in the thread).


Your example doesn't remotely do what the OP was asking for.  In fact
your example is so preposterous I question your sanity.


Your first sentence is incorrect, your second sentence is a silly attempt at 
getting personal.




However, it's IMHO an abuse of the language, not something that one should do.


Usually people abuse the language to achieve something (ostensibly)
useful.  Your example is so useless I don't think I would even call it
abuse.


You are correct that it's useless. The OP asked for a construct to do a useless 
thing. The presented construct does exactly what the OP asked for: useless.




As best as I can tell, what it is is you attempting to make yourself
look like some kind of badass by answering some absurdly literal
interpretation of the OP's question.


Hm, there are ways to do things, even the ad hominem thing. You just present 
yourself as one using strong words when you're proven wrong. Myself I'm not 
foreign to strong words :-), but I wouldn't dream of applying them to a person.


The above is very, uh, primitive.

Besides, it's quite silly to get angry when you're proved to be wrong. :-)



Except you haven't even done that:

class using_directions:
up = 42
move( up )
print up # <- clearly not confined to context of function call


You know, I didn't think of that ingenious thing, that it would be possible to 
*modify* the example so that it no longer fit the OP's literal description. Thx!



Cheers & hth.,

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


Re: Sorted dictionary

2010-01-21 Thread Jan Kaliszewski

Dnia 21-01-2010 o 09:27:52 Raymond Hettinger  napisał(a):


On Jan 20, 5:02 pm, "Jan Kaliszewski"  wrote:



http://code.activestate.com/recipes/576998/



Using an underlying list to track sorted items
means that insertion and deletion take O(n) time.
That could be reduced to O(log n) time by using
a blist or skiplist as the underlying structure
for maintaining a sort.


Please note that I used funcions from bisect, that use binary search.

Doesn't it take O(log n) time?

*j

--
Jan Kaliszewski (zuo) 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Symbols as parameters?

2010-01-21 Thread Alf P. Steinbach

* Diez B. Roggisch:

Am 21.01.10 12:58, schrieb Alf P. Steinbach:

* Stefan Behnel:

Alf P. Steinbach, 21.01.2010 11:38:

* Carl Banks:

On Jan 20, 11:43 pm, Martin Drautzburg 

[snip]

What I am really looking for is a way

- to be able to call move(up)
- having the "up" symbol only in the context of the function
call

Short answer is, you can't do it.


On the contrary, it's not difficult to do.

I provided an example in my answer to the OP (first reply in the
thread).


Erm, no, you didn't. You showed a) how to pass a string constant into a
function and b) how to pass a value from a bound variable. None of
that is
helpful to the OP's problem.


Perhaps look again at that example. It demonstrates exactly what the OP
asks for.


Perhaps look again at the requirements:

"""
  - the parameter IS REALLY NOT A STRING, but a direction
"""


So?


Cheers & hth.,

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


Re: Symbols as parameters?

2010-01-21 Thread Diez B. Roggisch

Am 21.01.10 19:48, schrieb Alf P. Steinbach:

* Diez B. Roggisch:

Am 21.01.10 12:58, schrieb Alf P. Steinbach:

* Stefan Behnel:

Alf P. Steinbach, 21.01.2010 11:38:

* Carl Banks:

On Jan 20, 11:43 pm, Martin Drautzburg 

[snip]

What I am really looking for is a way

- to be able to call move(up)
- having the "up" symbol only in the context of the function
call

Short answer is, you can't do it.


On the contrary, it's not difficult to do.

I provided an example in my answer to the OP (first reply in the
thread).


Erm, no, you didn't. You showed a) how to pass a string constant into a
function and b) how to pass a value from a bound variable. None of
that is
helpful to the OP's problem.


Perhaps look again at that example. It demonstrates exactly what the OP
asks for.


Perhaps look again at the requirements:

"""
- the parameter IS REALLY NOT A STRING, but a direction
"""


So?


Oh please. You claim you provided exactly what the OP asked for. But in 
the body of move, all you can do is to compare the direction parameter 
tco "up", not to UP. So no, you provided *something*, but not what the 
OP asked for.


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


Re: Symbols as parameters?

2010-01-21 Thread Alf P. Steinbach

* Diez B. Roggisch:

Am 21.01.10 19:48, schrieb Alf P. Steinbach:

* Diez B. Roggisch:

Am 21.01.10 12:58, schrieb Alf P. Steinbach:

* Stefan Behnel:

Alf P. Steinbach, 21.01.2010 11:38:

* Carl Banks:

On Jan 20, 11:43 pm, Martin Drautzburg 

[snip]

What I am really looking for is a way

- to be able to call move(up)
- having the "up" symbol only in the context of the function
call

Short answer is, you can't do it.


On the contrary, it's not difficult to do.

I provided an example in my answer to the OP (first reply in the
thread).


Erm, no, you didn't. You showed a) how to pass a string constant 
into a

function and b) how to pass a value from a bound variable. None of
that is
helpful to the OP's problem.


Perhaps look again at that example. It demonstrates exactly what the OP
asks for.


Perhaps look again at the requirements:

"""
- the parameter IS REALLY NOT A STRING, but a direction
"""


So?


Oh please. You claim you provided exactly what the OP asked for. But in 
the body of move, all you can do is to compare the direction parameter 
tco "up", not to UP. So no, you provided *something*, but not what the 
OP asked for.


Pardon me for not taking you seriously or not getting the joke, if that's what 
it's meant as.



Cheers,

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


Re: Symbols as parameters?

2010-01-21 Thread Diez B. Roggisch

Am 21.01.10 20:01, schrieb Alf P. Steinbach:

* Diez B. Roggisch:

Am 21.01.10 19:48, schrieb Alf P. Steinbach:

* Diez B. Roggisch:

Am 21.01.10 12:58, schrieb Alf P. Steinbach:

* Stefan Behnel:

Alf P. Steinbach, 21.01.2010 11:38:

* Carl Banks:

On Jan 20, 11:43 pm, Martin Drautzburg 

[snip]

What I am really looking for is a way

- to be able to call move(up)
- having the "up" symbol only in the context of the function
call

Short answer is, you can't do it.


On the contrary, it's not difficult to do.

I provided an example in my answer to the OP (first reply in the
thread).


Erm, no, you didn't. You showed a) how to pass a string constant
into a
function and b) how to pass a value from a bound variable. None of
that is
helpful to the OP's problem.


Perhaps look again at that example. It demonstrates exactly what
the OP
asks for.


Perhaps look again at the requirements:

"""
- the parameter IS REALLY NOT A STRING, but a direction
"""


So?


Oh please. You claim you provided exactly what the OP asked for. But
in the body of move, all you can do is to compare the direction
parameter tco "up", not to UP. So no, you provided *something*, but
not what the OP asked for.


Pardon me for not taking you seriously or not getting the joke, if
that's what it's meant as.


No joking, unless you started it somewhere earlier. The OP didn't want 
to compare to a string, yet your "example" forces him to exactly do 
that. If not, would you care to show us the fulfillment of "the 
parameter IS REALLY NOT A STRING, but a direction" in your example? Thanks.


You see, it seems that you agreeing to be wrong is something your are so 
adamantly refusing to acknowledge that I'm inclined to believe that in 
the event of this really happen one day, a great rift in the very fabric 
of space and time would appear, and the world would end. If this 
conversation was in my native language and not in yours, I'd might give 
it a shot, just to see what really happens. But as it isn't, and I guess 
everybody else except you knows that your wrong - I wont.


HTH,

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


Re: Closures in metaclasses

2010-01-21 Thread Arnaud Delobelle
On Jan 21, 6:37 pm, Falcolas  wrote:
> On Jan 21, 11:24 am, Arnaud Delobelle  wrote:
>
>
>
>
>
> > Falcolas  writes:
> > > I'm running into an issue with closures in metaclasses - that is, if I
> > > create a function with a closure in a metaclass, the closure appears
> > > to be lost when I access the final class. I end up getting the text
> > > 'param' instead of the actual tags I am expecting:
>
> > > ALL_TAGS =  ['a', 'abbr', 'acronym', 'address', 'applet', 'b', 'bdo',
> > > 'big'] #snip
>
> > > def _tag_meta(name, bases, dict_):
> > >     for tag in ALL_TAGS:
> > >         def generic_tag(*args, **kwargs):
> > >             return Tag._generate_tag(tag, *args, **kwargs)
> > >         #generic_tag = eval("lambda *args, **kwargs: Tag._generate_tag
> > > ('%s', *args, **kwargs)" % tag)
> > >         dict_[tag] = staticmethod(generic_tag)
> > >     return type(name, bases, dict_)
>
> > This is almost a FAQ and has nothing to do with metaclasses.  The
> > simplest solution usually involves adding a default argument 'tag=tag'
> > to the function you define (here, generic_tag), but you can't do this
> > here because you have a **kwargs argument.  Instead, you can use a
> > closure and do this for example:
>
> > def factory(tag):
> >     def generic_tag(*args, **kwargs):
> >         return Tag._generate_tag(tag, *args, **kwargs)
> >     return generic_tag
>
> > def _tag_meta(name, bases, dict_):
> >     for tag in ALL_TAGS:
> >         dict_[tag] = staticmethod(factory(tag))
> >     return type(name, bases, dict_)
>
> I see - I was thinking it would preserve the closure from the for
> statement, but I can see now why that would be wrong.
>
>
>
> > However, I am usure about why you are using a metaclass.
>
> > HTH
>
> > --
> > Arnaud
>
> It was the easiest way I found to add a lot of static methods to the
> Tag class without writing each one out. __getattr__ was not working
> for this application. This is for a very simple application, and I
> didn't want to add a lot of complexity to it's use. I'm always open
> for other options OTOH.

This should work (untested):

class Tag(object):
@staticmethod
def _generate_tag(tag_name, *args, **kwargs):
# Does the expected, following is just for the example's sake
return tag

for tag in ALL_TAGS:
setattr(Tag, tag, staticmethod(factory(tag)))

Or you could override __getattr__

--
Arnaud


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


Re: Symbols as parameters?

2010-01-21 Thread Alf P. Steinbach

* Diez B. Roggisch:

Am 21.01.10 20:01, schrieb Alf P. Steinbach:

* Diez B. Roggisch:

Am 21.01.10 19:48, schrieb Alf P. Steinbach:

* Diez B. Roggisch:

Am 21.01.10 12:58, schrieb Alf P. Steinbach:

* Stefan Behnel:

Alf P. Steinbach, 21.01.2010 11:38:

* Carl Banks:

On Jan 20, 11:43 pm, Martin Drautzburg 

[snip]

What I am really looking for is a way

- to be able to call move(up)
- having the "up" symbol only in the context of the function
call

Short answer is, you can't do it.


On the contrary, it's not difficult to do.

I provided an example in my answer to the OP (first reply in the
thread).


Erm, no, you didn't. You showed a) how to pass a string constant
into a
function and b) how to pass a value from a bound variable. None of
that is
helpful to the OP's problem.


Perhaps look again at that example. It demonstrates exactly what
the OP
asks for.


Perhaps look again at the requirements:

"""
- the parameter IS REALLY NOT A STRING, but a direction
"""


So?


Oh please. You claim you provided exactly what the OP asked for. But
in the body of move, all you can do is to compare the direction
parameter tco "up", not to UP. So no, you provided *something*, but
not what the OP asked for.


Pardon me for not taking you seriously or not getting the joke, if
that's what it's meant as.


No joking, unless you started it somewhere earlier. The OP didn't want 
to compare to a string, yet your "example" forces him to exactly do 
that. If not, would you care to show us the fulfillment of "the 
parameter IS REALLY NOT A STRING, but a direction" in your example? Thanks.


Just use a "direction" instead of a number (if you didn't like the number).

I'm sorry that I couldn't believe that you didn't understand that.

But OK, you didn't.

The OP gave no definition of his "direction" though, so you'll have to use your 
good sense about possibilities for what it could be.


From the context and later comments (especially about "import") my guess us 
that he's talking about numbers denoting directions, but you'd have to ask him.



You see, it seems that you agreeing to be wrong is something your are so 
adamantly refusing to acknowledge that I'm inclined to believe that in 
the event of this really happen one day, a great rift in the very fabric 
of space and time would appear, and the world would end. If this 
conversation was in my native language and not in yours, I'd might give 
it a shot, just to see what really happens. But as it isn't, and I guess 
everybody else except you knows that your wrong - I wont.


The above is a silly ad hominem attack, containing 1 lie, and trying to confuse 
the issue: you're posting this in a different part of the thread as a response 
to Carls Banks being proved wrong by my example. Incidentally, he also resorts 
to ad hominem. Sadly it seems to be a common response pattern in this group.


Do you understand how bad that makes you look?


Cheers & hth.,

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


Re: multiprocessing as batch system

2010-01-21 Thread Neal Becker
Adam Tauno Williams wrote:

> On Thu, 2010-01-21 at 07:13 -0500, Neal Becker wrote:
>> I'm using multiprocessing as a poor man's batch system.  It is working
>> OK, except that it doesn't seem to do load balancing quite right.
>> I have a 8-cpu machine.  If I start, using multiprocessing pool, calling
>> map
>> with more than 8 elements, it will start 8 processes.  It seems, though,
>> that when some of them finish, it does not start others right away.  The
>> load average may be a lot less than 8 but still additional processes are
>> not active.
> 
> If your processes are I/O bound your system will never appear to be
> saturated.  Multiple pending processes and a low load average usually
> indicated waiting on some other resource.
No, 100% compute bound.

My impression was that some processes completed, but new ones were not 
immediately started.

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


Re: Sorted dictionary

2010-01-21 Thread Daniel Stutzbach
On Thu, Jan 21, 2010 at 12:45 PM, Jan Kaliszewski  wrote:

> Please note that I used funcions from bisect, that use binary search.
>
> Doesn't it take O(log n) time?
>

It takes O(log n) time to find the point to insert, but O(n) time to perform
the actual insertion.

--
Daniel Stutzbach, Ph.D.
President, Stutzbach Enterprises, LLC 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorted dictionary

2010-01-21 Thread Arnaud Delobelle
"Jan Kaliszewski"  writes:

> Dnia 21-01-2010 o 09:27:52 Raymond Hettinger  napisał(a):
>
>> On Jan 20, 5:02 pm, "Jan Kaliszewski"  wrote:
>
>>> http://code.activestate.com/recipes/576998/
>
>> Using an underlying list to track sorted items
>> means that insertion and deletion take O(n) time.
>> That could be reduced to O(log n) time by using
>> a blist or skiplist as the underlying structure
>> for maintaining a sort.
>
> Please note that I used funcions from bisect, that use binary search.
>
> Doesn't it take O(log n) time?

Insertion and deletion are still O(n) as all items to the right of the
inserted/deleted one have to be shifted by one place.

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


Re: Symbols as parameters?

2010-01-21 Thread Carl Banks
On Jan 21, 10:46 am, "Alf P. Steinbach"  wrote:
> * Carl Banks:
>
>
>
>
>
> > On Jan 21, 2:38 am, "Alf P. Steinbach"  wrote:
> >> * Carl Banks:
>
> >>> On Jan 20, 11:43 pm, Martin Drautzburg 
> >> [snip]
>
>  What I am really looking for is a way
>          - to be able to call move(up)
>          - having the "up" symbol only in the context of the function call
> >>> Short answer is, you can't do it.
> >> On the contrary, it's not difficult to do.
>
> >> I provided an example in my answer to the OP (first reply in the thread).
>
> > Your example doesn't remotely do what the OP was asking for.  In fact
> > your example is so preposterous I question your sanity.
>
> Your first sentence is incorrect, your second sentence is a silly attempt at
> getting personal.
>
> >> However, it's IMHO an abuse of the language, not something that one should 
> >> do.
>
> > Usually people abuse the language to achieve something (ostensibly)
> > useful.  Your example is so useless I don't think I would even call it
> > abuse.
>
> You are correct that it's useless. The OP asked for a construct to do a 
> useless
> thing. The presented construct does exactly what the OP asked for: useless.
>
> > As best as I can tell, what it is is you attempting to make yourself
> > look like some kind of badass by answering some absurdly literal
> > interpretation of the OP's question.
>
> Hm, there are ways to do things, even the ad hominem thing. You just present
> yourself as one using strong words when you're proven wrong. Myself I'm not
> foreign to strong words :-), but I wouldn't dream of applying them to a 
> person.
>
> The above is very, uh, primitive.
>
> Besides, it's quite silly to get angry when you're proved to be wrong. :-)
>
> > Except you haven't even done that:
>
> > class using_directions:
> >     up = 42
> >     move( up )
> >     print up # <- clearly not confined to context of function call
>
> You know, I didn't think of that ingenious thing, that it would be possible to
> *modify* the example so that it no longer fit the OP's literal description. 
> Thx!

I'm not sure if you're trolling, insane, or just stupid; regardless,
I'm done with you.


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


Re: Symbols as parameters?

2010-01-21 Thread Alf P. Steinbach

* Carl Banks:

On Jan 21, 10:46 am, "Alf P. Steinbach"  wrote:

* Carl Banks:

On Jan 21, 2:38 am, "Alf P. Steinbach"  wrote:

* Carl Banks:

On Jan 20, 11:43 pm, Martin Drautzburg 

[snip]

What I am really looking for is a way
- to be able to call move(up)
- having the "up" symbol only in the context of the function call

Short answer is, you can't do it.

On the contrary, it's not difficult to do.
I provided an example in my answer to the OP (first reply in the thread).

Your example doesn't remotely do what the OP was asking for.  In fact
your example is so preposterous I question your sanity.

Your first sentence is incorrect, your second sentence is a silly attempt at
getting personal.


However, it's IMHO an abuse of the language, not something that one should do.

Usually people abuse the language to achieve something (ostensibly)
useful.  Your example is so useless I don't think I would even call it
abuse.

You are correct that it's useless. The OP asked for a construct to do a useless
thing. The presented construct does exactly what the OP asked for: useless.


As best as I can tell, what it is is you attempting to make yourself
look like some kind of badass by answering some absurdly literal
interpretation of the OP's question.

Hm, there are ways to do things, even the ad hominem thing. You just present
yourself as one using strong words when you're proven wrong. Myself I'm not
foreign to strong words :-), but I wouldn't dream of applying them to a person.

The above is very, uh, primitive.

Besides, it's quite silly to get angry when you're proved to be wrong. :-)


Except you haven't even done that:
class using_directions:
up = 42
move( up )
print up # <- clearly not confined to context of function call

You know, I didn't think of that ingenious thing, that it would be possible to
*modify* the example so that it no longer fit the OP's literal description. Thx!


I'm not sure if you're trolling, insane, or just stupid; regardless,
I'm done with you.


Piling more ad hominem attacks on top of your previous is pretty silly.

You were technically wrong, that's no big issue, everybody is wrong now and 
then.

But reacting to a polite notification of your error, by going all out with 
various personal accusations, doesn't give anybody a positive impression of you.



Cheers & hth.,

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


Re: counting lines of code

2010-01-21 Thread Phlip
On Jan 20, 11:20 pm, Michele Simionato 
wrote:

> pylint does too many things, I want something fast that just counts
> the lines and can be run on thousands of files at once.
> cloc seems fine, I have just tried on 2,000 files and it gives me a
> report in just a few seconds.

In my experience with Python codebases that big...

...how many of those lines are duplicated, and might merge together
into a better design?

The LOC would go down, too.

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


Re: Dynamic HTML controls

2010-01-21 Thread Aahz
In article ,
Alan Harris-Reid   wrote:
>
>Does anyone know where I can find any decent dynamically-constructed 
>HTML control classes (dropdown list, table, input field, checkbox, etc.) 
>written in Python.  For example, for a HTML table I would like something 
>like...

You might look at Quixote:
http://quixote.ca/
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

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


Re: Closures in metaclasses

2010-01-21 Thread Falcolas
On Jan 21, 12:10 pm, Arnaud Delobelle  wrote:
> On Jan 21, 6:37 pm, Falcolas  wrote:
>
> > On Jan 21, 11:24 am, Arnaud Delobelle  wrote:
>
> > It was the easiest way I found to add a lot of static methods to the
> > Tag class without writing each one out. __getattr__ was not working
> > for this application. This is for a very simple application, and I
> > didn't want to add a lot of complexity to it's use. I'm always open
> > for other options OTOH.
>
> This should work (untested):
>
> class Tag(object):
>     @staticmethod
>     def _generate_tag(tag_name, *args, **kwargs):
>         # Does the expected, following is just for the example's sake
>         return tag
>
> for tag in ALL_TAGS:
>     setattr(Tag, tag, staticmethod(factory(tag)))
>
> Or you could override __getattr__
>
> --
> Arnaud

I tried overriding __getattr__ and got an error at runtime (the
instance did not have xyz key, etc), and the Tag dict is not
modifiable (granted, I tried Tag.__dict__[tag] = spam, not setattr()).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Closures in metaclasses

2010-01-21 Thread Peter Otten
Falcolas wrote:

> I tried overriding __getattr__ and got an error at runtime (the

You can either move __getattr__() into the metaclass or instantiate the 
class. I prefer the latter.

Both approaches in one example:

>>> class Tag:
... class __metaclass__(type):
... def __getattr__(self, name): return "<%s> via metaclass" % 
name
... def __getattr__(self, name): return "<%s> via class" % name
...
>>> Tag.yadda
' via metaclass'
>>> tag = Tag()
>>> tag.yadda
' via class'


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


Re: what test runner should I use?

2010-01-21 Thread Lacrima
On Jan 19, 12:56 pm, Chris Withers  wrote:
> Hi All,
>
> I'm wondering what test runner I should use. Here's my list of requirements:
>
> - cross platform (I develop for and on Windows, Linux and Mac)
>
> - should not prevent tests from running with other test runners
>    (so no plugins/layers/etc that only work with one specific test
>     runner)
>
> - should work with zc.buildout (preferably without a specialist recipe!)
>
> So far I've tried the following with the resultant problems:
>
> zope.testing
>
>   - requires a special recipe to be useful
>   - now emits deprecation warnings from itself:
>    https://mail.zope.org/pipermail/zope-dev/2009-December/038965.html
>   - coverage support is baroque to put it politely
>
> twisted's trial
>
>   - only has old-style script definition in setup.py, so doesn't work
>     with buildout without hackery
>
>   - drops _twisted_trial folders all over the place and doesn't clear
>     them up
>
> nose
>
>   - can't see to get it to run only my packages tests, rather than
>     including the tests of packages my package depends on
>
>   - seems to be focused towards files rather than modules
>     (which makes it not play nicely with buildout)
>
>   - seems to be difficult to provide options to at configuration time
>     that can then be overridden on the command line
>
> I did also look at py.test's homepage but found it pretty scary.
>
> What other options do people recommend?
> Failing that, any ideas how to fix the problems above?
>
> cheers,
>
> Chris

Nose should work pretty well with buildout. You need this in your
buildout.cfg

[buildout]
parts = test

[test]
recipe = pbp.recipe.noserunner
eggs = yourpackage1 yourpackage2

This will generate test script (bin/test), which will search and run
tests only in packages, specified in eggs option.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Closures in metaclasses

2010-01-21 Thread Falcolas
On Jan 21, 1:55 pm, Peter Otten <__pete...@web.de> wrote:
> Falcolas wrote:
> > I tried overriding __getattr__ and got an error at runtime (the
>
> You can either move __getattr__() into the metaclass or instantiate the
> class. I prefer the latter.
>
> Both approaches in one example:
>
> >>> class Tag:
>
> ...     class __metaclass__(type):
> ...             def __getattr__(self, name): return "<%s> via metaclass" %
> name
> ...     def __getattr__(self, name): return "<%s> via class" % name
> ...>>> Tag.yadda
>
> ' via metaclass'>>> tag = Tag()
> >>> tag.yadda
>
> ' via class'

Very nice, thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Closures in metaclasses

2010-01-21 Thread Arnaud Delobelle
Falcolas  writes:

> On Jan 21, 12:10 pm, Arnaud Delobelle  wrote:
[...]
>> Or you could override __getattr__
>>
>> --
>> Arnaud
>
> I tried overriding __getattr__ and got an error at runtime (the
> instance did not have xyz key, etc), and the Tag dict is not
> modifiable (granted, I tried Tag.__dict__[tag] = spam, not setattr()).

Yes that's because __getattr__ works on instances, not on the class
itself.  To achieve this, you'd have to override the *metaclass*'s
__getattr__ method.

But are you sure that you want lots of staticmethods?  Why not
instanciate your class Tag instead and have normal methods to generate
tags?  This would have the added benefit that you could set some options
in the __init__ method of Tag to customize its behaviour.

If you have a class which only contains static methods, you'd be better
off with a module which contains good old functions.

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


Re: simple pub/sub

2010-01-21 Thread Steve Howell
On Jan 21, 9:37 am, a...@pythoncraft.com (Aahz) wrote:
> In article 
> <0af0eff2-50e2-44aa-81f1-b3d12cb26...@a15g2000yqm.googlegroups.com>,
> Steve Howell   wrote:
>
>
>
> >Hi, I'm looking for ideas on building a simple architecture that
> >allows a bunch of independent Python processes to exchange data using
> >files and perform calculations.
>
> SQLite?

The data is just a stream of instrument readings, so putting it into a
relational database doesn't really buy me much.  So far
"multiprocessing" seems to be the way to go.

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


Rounding up to the next 100

2010-01-21 Thread noydb
If one has a floating number as a string, is there a spiffy way to
round that string-number UP to the nearest 100?

XstrNmbr = 3579.127893 -- would want to round that to 3600.

Thanks for any help!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: counting lines of code

2010-01-21 Thread Aahz
In article <7e09df6a-cda1-480e-a971-8f8a70ac4...@b9g2000yqd.googlegroups.com>,
Phlip   wrote:
>On Jan 20, 11:20=A0pm, Michele Simionato 
>wrote:
>>
>> pylint does too many things, I want something fast that just counts
>> the lines and can be run on thousands of files at once.
>> cloc seems fine, I have just tried on 2,000 files and it gives me a
>> report in just a few seconds.
>
>In my experience with Python codebases that big...
>
>...how many of those lines are duplicated, and might merge together
>into a better design?

Um... do you have any clue who you followed up to?  If you don't, Google
is your friend.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

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


Re: py2exe and pydocs. Downloads?

2010-01-21 Thread Gib Bogle

Gabriel Genellina wrote:

You found a bug. Looks like it depends on the environment, or what 
packages are installed, or something like that, because it worked on my 
other PC but not here.

Please report it at http://bugs.python.org so it doesn't get forgotten.



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


Re: Python and Tkinter Programming by John Grayson

2010-01-21 Thread Peter
On Jan 15, 9:12 am, Kevin Walzer  wrote:
> On 1/14/10 3:39 PM, Peter wrote:
>
>
>
>
>
> > On Jan 15, 6:24 am, Mark Roseman  wrote:
> >>   Peter  wrote:
> >>> Besides, the book is mainly about using Python with Tkinter - and
> >>> Tkinter hasn't changed that much since 2000, so I believe it is just
> >>> as relevant today as it was back then.
>
> >> I'd say that Tkinter has substantially changed - with the introduction
> >> of the 'ttk' themed widgets.  I cover these in my tutorial 
> >> athttp://www.tkdocs.com
>
> >> Mark
>
> > But is the ttk themed widgets a "change" to Tkinter or an "addition/
> > improvement"? i.e. does the themed widgets invalidate any of the
> > Tkinter stuff in Grayson's book? That certainly isn't my impression of
> > the themed widgets, I was of the impression that the themed widgets
> > just added some convenient widgets (such as Scale, Spinbox etc) which
> > a user could find in other GUI frameworks, for example, Pmw
> > supplemented the basic Tkinter widget set and offered some (essential
> > IMO) widgets that were missing in Tkinter - such as the Notebook
> > widget.
>
> It's both a change and an improvement. The themed widgets can be used in
> conjunction with the traditional widgets, but in many cases it's
> possible (and desirable) to update your entire application to use the
> themed widgets.
>
> > Lets face it, if somebody wants to get up to speed on Python and GUI
> > development then the book is still very, very relevant and necessary
> > (IMO). The documentation for the themed widgets still leaves a lot to
> > be desired from the perspective of somebody who wants to start using
> > Python to create GUI applications. As Lord Eldritch reminded me in his
> > post, the book even has a section on Pmw - which is what I use mainly
> > for my GUI applications - because Tkinter was missing some vital
> > widgets that are now available in the ttk themed set.
>
> > Personally I will start to incorporate some of the ttk themed widgets
> > into my applications - but Pmw will remain the 'basis' for my GUI's as
> > the entire framework (IMO) supports a class oriented approach that
> > allows easy creation of extensible and reconfigurable (at run time)
> > GUI interfaces.
>
> PMW is certainly a helpful addition to the Tkinter developer's toolbox,
> but it also has limitations. It suffers from some of the same
> limitations as Tk itself, i.e. it is rather dated in appearance, and
> even it lacks some modern UI features such as a good multicolumn
> listbox, treeview, etc. In addition to the ttk themed widgets, other,
> more configurable pure Tk-based megawidget packages exist, such as
> BWidgets and Tablelist, and there are Python wrappers for these at the
> Tkinter wiki (http://tkinter.unpythonic.net/wiki/).
>
>
>
> > Ultimately Grayson does a good job of providing information and
> > reference to toolkit(s) that allow a beginner to quickly get up to
> > speed on producing a GUI using Python. It is purely up to the user
> > afterwards as to whether they stick with Tkinter/Pmw (and now the ttk
> > themed set) or venture into wxPython or Jython (as two examples of GUI
> > 'systems' that provide 'better' facilities to a Python programmer).
>
> Another book I've found very helpful for learning Tkinter is Programming
> Python by Mark Lutz--a lot of coverage there of GUI development.
>
> --Kevin
>
> --
> Kevin Walzer
> Code by Kevinhttp://www.codebykevin.com

Another possible consideration when choosing a GUI to learn Python -
will you want to print from within your GUI application? Admittedly, I
haven't looked to see whether this situation has changed or not for
some years now, but a GUI based on Tkinter (whether it is ttk or Pmw
or whatever) has no support for "printing". Other GUI frameworks, such
as wxPython, Jython, PyQT etc have API's that allow printing of
information from within your GUI application.

Now if you go the Tk route, I am sure you can use the Win32 bindings
to do printing - but I personally could never work them out :-) Maybe
there is some reasonable documentation or example code for doing that
these days - but there wasn't when I first approached the problem
(which was back in the python 2.1 days - ancient history!). Printing
using Windows API was a complete mystery to me.

My first GUI application required information to be printed out - I
wrote the whole thing using Pmw and Tkinter - only to find that I had
no way of getting stuff to a printer (I was learning Python and
Tkinter at the time :-)). I briefly explored "porting" my application
to wxPython or Jython because both frameworks provided printer API
functions - at that time, PyQT was commercial license only for a PC,
so that wasn't an option. I found wxPython stunningly hard to
understand from the documentation (I have since purchased wxPython in
Action by Rappin and Dunn but have never found the time to read it). I
had some problems porting the code to Jython (my code relied heavily
on the pickle module and Jython 

Re: counting lines of code

2010-01-21 Thread Phlip

Aahz wrote:

In article <7e09df6a-cda1-480e-a971-8f8a70ac4...@b9g2000yqd.googlegroups.com>,
Phlip   wrote:

On Jan 20, 11:20=A0pm, Michele Simionato 
wrote:

pylint does too many things, I want something fast that just counts
the lines and can be run on thousands of files at once.
cloc seems fine, I have just tried on 2,000 files and it gives me a
report in just a few seconds.

In my experience with Python codebases that big...

...how many of those lines are duplicated, and might merge together
into a better design?


Um... do you have any clue who you followed up to?  If you don't, Google
is your friend.


Oh, sorry, did I have the wrong opinion?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rounding up to the next 100

2010-01-21 Thread Arnaud Delobelle
noydb  writes:

> If one has a floating number as a string, is there a spiffy way to
> round that string-number UP to the nearest 100?
>
> XstrNmbr = 3579.127893 -- would want to round that to 3600.
>
> Thanks for any help!

>>> XstrNmbr = 3579.127893
>>> round(float(XstrNmbr), -2)
3600.0
>>> 

HTH

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


Re: Rounding up to the next 100

2010-01-21 Thread Arnaud Delobelle
Arnaud Delobelle  writes:


> >>> XstrNmbr = 3579.127893

I meant
>>> XstrNmbr = "3579.127893"

> >>> round(float(XstrNmbr), -2)
> 3600.0

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


RE: Rounding up to the next 100

2010-01-21 Thread Michael . Coll-Barth
 

> From: noydb

> If one has a floating number as a string, is there a spiffy way to
> round that string-number UP to the nearest 100?
> 
> XstrNmbr = 3579.127893 -- would want to round that to 3600.


What's wrong with round?  round( XstrNmbr, -2 ) seems to do the trick.
Or do you want to get rid of the decimal point as well?


The information contained in this message and any attachment may be
proprietary, confidential, and privileged or subject to the work
product doctrine and thus protected from disclosure.  If the reader
of this message is not the intended recipient, or an employee or
agent responsible for delivering this message to the intended
recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited.
If you have received this communication in error, please notify me
immediately by replying to this message and deleting it and all
copies and backups thereof.  Thank you.


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


Re: Rounding up to the next 100

2010-01-21 Thread Florian Diesch
noydb  writes:

> If one has a floating number as a string, is there a spiffy way to
> round that string-number UP to the nearest 100?
>
> XstrNmbr = 3579.127893 -- would want to round that to 3600.

math.ceil(3579.127893/100)*100


   Florian
-- 
GUIs programmieren mit Python und Glade:

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


Re: Rounding up to the next 100

2010-01-21 Thread Alf P. Steinbach

* michael.coll-ba...@verizonwireless.com:
 


From: noydb



If one has a floating number as a string, is there a spiffy way to
round that string-number UP to the nearest 100?

XstrNmbr = 3579.127893 -- would want to round that to 3600.



What's wrong with round?  round( XstrNmbr, -2 ) seems to do the trick.
Or do you want to get rid of the decimal point as well?


Perhaps completely irrelevant, but just in passing, round() changed semantics 
from 2.x to 3.x, in 3.x always returning int when called with just 1 argument:



  >>> import sys
  >>> sys.version
  '2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)]'
  >>> print round.__doc__
  round(number[, ndigits]) -> floating point number

  Round a number to a given precision in decimal digits (default 0 digits).
  This always returns a floating point number.  Precision may be negative.
  >>> _


  >>> import sys
  >>> sys.version
  '3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)]'
  >>> print( round.__doc__ )
  round(number[, ndigits]) -> number

  Round a number to a given precision in decimal digits (default 0 digits).
  This returns an int when called with one argument, otherwise the
  same type as the number. ndigits may be negative.
  >>> _


Might be useful to know regarding "get rid of the decimal point": in 3.x 
round(x) does that, in 2.x it doesn't.



Cheers,

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


Re: Rounding up to the next 100

2010-01-21 Thread noydb
On Jan 21, 4:30 pm, michael.coll-ba...@verizonwireless.com wrote:
> > From: noydb
> > If one has a floating number as a string, is there a spiffy way to
> > round that string-number UP to the nearest 100?
>
> > XstrNmbr = 3579.127893 -- would want to round that to 3600.
>
> What's wrong with round?  round( XstrNmbr, -2 ) seems to do the trick.
> Or do you want to get rid of the decimal point as well?
>
> The information contained in this message and any attachment may be
> proprietary, confidential, and privileged or subject to the work
> product doctrine and thus protected from disclosure.  If the reader
> of this message is not the intended recipient, or an employee or
> agent responsible for delivering this message to the intended
> recipient, you are hereby notified that any dissemination,
> distribution or copying of this communication is strictly prohibited.
> If you have received this communication in error, please notify me
> immediately by replying to this message and deleting it and all
> copies and backups thereof.  Thank you.

Thanks Arnaud!

Michael - Nothing is wrong with round -- when I tried it initially, I
was confused on the base -- seeing it from this example helped clear
it up.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rounding up to the next 100

2010-01-21 Thread noydb
Sorry, although what I really need is the string-number rounded UP
every time.  So if the number is 3890.32, it needs to go to 3900; if
the number is 3811.345, it needs to go to 3900 also.

So, Florian's answer works.

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


RE: Rounding up to the next 100

2010-01-21 Thread Michael . Coll-Barth
 

> From: Arnaud Delobelle
> 
> 
> > >>> XstrNmbr = 3579.127893
> 
> I meant
> >>> XstrNmbr = "3579.127893"
> 
> > >>> round(float(XstrNmbr), -2)
> > 3600.0

Ah, then you will need to cast it first.

>>> XstrNmbr = '3579.127893'
>>> round(float(XstrNmbr) ,-2)
3600.0



The information contained in this message and any attachment may be
proprietary, confidential, and privileged or subject to the work
product doctrine and thus protected from disclosure.  If the reader
of this message is not the intended recipient, or an employee or
agent responsible for delivering this message to the intended
recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited.
If you have received this communication in error, please notify me
immediately by replying to this message and deleting it and all
copies and backups thereof.  Thank you.


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


Re: py2exe and pydocs. Downloads?

2010-01-21 Thread Gib Bogle

Gabriel Genellina wrote:
En Wed, 20 Jan 2010 21:22:19 -0300, Gib Bogle 
 escribió:



Gabriel Genellina wrote:


c:\temp>python -m pydoc sys
Help on built-in module sys:
[...same info...]


When I do this I get:

No module named tempfile


You found a bug. Looks like it depends on the environment, or what 
packages are installed, or something like that, because it worked on my 
other PC but not here.

Please report it at http://bugs.python.org so it doesn't get forgotten.



The bug checkers are not able to reproduce the error.  What is your other PC 
running?

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


Re: Rounding up to the next 100

2010-01-21 Thread Alf P. Steinbach

* noydb:

Sorry, although what I really need is the string-number rounded UP
every time.  So if the number is 3890.32, it needs to go to 3900; if
the number is 3811.345, it needs to go to 3900 also.

So, Florian's answer works.


You might also consider

  -100*(-3579.127893//100)

:-)

Which avoids the math.ceil but assumes the number is positive (or zero).


Cheers & hth.,

- Alf

PS: Note that this trick doesn't work with most other common languages that I'm 
familiar with, since the round towards zero instead of down to minus infinity, 
but Python has more clean semantics in this regard.

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


Re: Symbols as parameters?

2010-01-21 Thread Martin Drautzburg
Thanks for all the answers. Let me summarize

(1) I fail to see the relevance of 
 >>> def move( direction ):
...   print( "move " + str( direction ) )
...
 >>> move( "up" )
move up

not only in the context of my question. And I don't see an abuse of the
language either. Maybe this could pass as a Zen Puzzle.

(2) Using enum's was suggested. That is good to know, but again it is
just a way to define constants in the caller's namespace.

(3) Then somone suggested to tie the constants to the function itself,
as in
def move(direction):
    print "moving %s" % direction

move.UP = 'up'
move.DOWN = 'down'

This is quite nice. Then again the "move." is just some object which
allows attributes, and which only happens to have the same name as the
function. Well in this case it IS the function, alright, but I could
just as well have used a Class as in

class m: pass
m.UP = 'up'


(4) Finally someone mentioned DSLs. I guess thats absolutely correct.
This is what I am struggeling to achieve. I did a little googling ("how
to write DSLs in python"), but haven't found anything appealing yet.
Any pointers would be appreciated.

(5) Here is something I came up with myself:

def symbols(aDict):
aDict["foo"] = "bar"

def someFunction(aFoo):
print aFoo

symbols(locals())
someFunction (foo) #Eh voila: foo is magically defined

prints: bar

The call to symbols(locals()) is the "magic, magic" I supected would be
required in my original posting. If someFunction was a member of a
class, the symbols would be properly tied to that class (albeit not the
individual function), but still good enough. I suppose I could wrap it
in a decorator, which would also do the "unmagic". 

In any case, getting the context right seems to be the biggest problem.
If I don't want to pollute my namespace, those symbols need to be
defined in some context but undefined in others. AFAIK there are not
really "blocks" in python and lexical scoping is present primarily in
functions. 




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


Re: Dynamic HTML controls

2010-01-21 Thread Alan Harris-Reid

Aahz wrote:

In article ,
Alan Harris-Reid   wrote:
  
Does anyone know where I can find any decent dynamically-constructed 
HTML control classes (dropdown list, table, input field, checkbox, etc.) 
written in Python.  For example, for a HTML table I would like something 
like...



You might look at Quixote:
http://quixote.ca/
  

Thanks for that Aahz - I'll check it out.

Regards,
Alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Symbols as parameters?

2010-01-21 Thread Alf P. Steinbach

* Martin Drautzburg:

Thanks for all the answers. Let me summarize

(1) I fail to see the relevance of 
 >>> def move( direction ):

...   print( "move " + str( direction ) )
...
 >>> move( "up" )
move up

not only in the context of my question. And I don't see an abuse of the
language either. Maybe this could pass as a Zen Puzzle.


Oh. You focused on the wrong details, then. Sorry for not providing a textual 
explanation, but I thought anyone not understanding it would just ask (that's 
normal in other Usenet groups that I'm familiar with).


So, explanation...

Here's your problem description, from the start of the thread:


What I am really looking for is a way

- to be able to call move(up)
- having the "up" symbol only in the context of the function call

So it should look something like this

... magic, magic ...
move(up)
... unmagic, unmagic ...
print up

This should complain that "up" is not defined during the "print" call,
but not when move() is called. And of course there should be as little
magic as possible.



The code corresponding to your first "magic, magic ..." is

class using_directions:
# Whatever statement (import?) defines symbolic directions goes here

Then comes your  --  note the added indentation

move( up )

Your "... unmagic, unmagic" is simply to go back to the previous indent level.

So your example's following

print up

at this point complaints that "up" is not defined, as you require (no general 
namespace pollution, although there is a slight but controllable pollution, 
namely the class name).


Not that I recommend this technique. ;-) But it does exactly what you asked, 
quoted above.


The best technique in my view is what you came up with yourself in the article 
I'm responding to (but snipped by me), namely a class with the constants and the 
function. It doesn't do what you required originally. But it's much better! :-)



Cheers & hth.,

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


Re: Symbols as parameters?

2010-01-21 Thread Diez B. Roggisch

Am 21.01.10 22:51, schrieb Martin Drautzburg:

Thanks for all the answers. Let me summarize

(1) I fail to see the relevance of
  >>>  def move( direction ):
...   print( "move " + str( direction ) )
...
  >>>  move( "up" )
move up

not only in the context of my question. And I don't see an abuse of the
language either. Maybe this could pass as a Zen Puzzle.

(2) Using enum's was suggested. That is good to know, but again it is
just a way to define constants in the caller's namespace.

(3) Then somone suggested to tie the constants to the function itself,
as in
def move(direction):
 print "moving %s" % direction

move.UP = 'up'
move.DOWN = 'down'

This is quite nice. Then again the "move." is just some object which
allows attributes, and which only happens to have the same name as the
function. Well in this case it IS the function, alright, but I could
just as well have used a Class as in

class m: pass
m.UP = 'up'


(4) Finally someone mentioned DSLs. I guess thats absolutely correct.
This is what I am struggeling to achieve. I did a little googling ("how
to write DSLs in python"), but haven't found anything appealing yet.
Any pointers would be appreciated.

(5) Here is something I came up with myself:

def symbols(aDict):
 aDict["foo"] = "bar"

def someFunction(aFoo):
 print aFoo

symbols(locals())
someFunction (foo) #Eh voila: foo is magically defined


http://docs.python.org/library/functions.html#locals

If it works, it's more an accident than anything else, and can go away 
without prior notice.



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


  1   2   >