Re: Speed of Python

2007-09-07 Thread Marc 'BlackJack' Rintsch
On Fri, 07 Sep 2007 23:53:48 +, wang frank wrote:

>>From: "Marc 'BlackJack' Rintsch" <[EMAIL PROTECTED]>
>>To: python-list@python.org
>>Subject: Re: Speed of Python
>>Date: 7 Sep 2007 23:17:55 GMT
>>
>>On Fri, 07 Sep 2007 22:59:26 +, wang frank wrote:
>>
>> > I also have tried to use numpy to speed it up. However, surprisingly, 
> it is
>> > slower than the pure python code.
>> >
>> > Here is the code:
>> > import  numpy
>> > arange=numpy.arange
>> > nlog=numpy.log
>> > def bench6(n):
>> >for i in xrange(n):
>> >for j in xrange(1000):
>> >m=j+1
>> >z=nlog(m)
>> >z1=nlog(m+1)
>> >z2=nlog(m+2)
>> >z3=nlog(m+3)
>> >z4=nlog(m+4)
>> >z5=nlog(m+5)
>> >z6=nlog(m+6)
>> >z7=nlog(m+7)
>> >z8=nlog(m+8)
>> >z9=nlog(m+9)
>> >return z9
>> >
>> > [窶ヲ]
>> >
>> > Anyone know why?
>>
>>Because you don't really take advantage of `numpy`.  The `numpy.log()`
>>function can be used with scalars but I guess it is slower because it has
>>to check if its argument is a scalar or array.  Untested:
>>
>>from numpy import arange, log as nlog
>>
>>def bench6(n):
>> for dummy in xrange(n):
>> for j in xrange(1000):
>> z = nlog(arange(j + 1, j + 11))
>> return z[-1]
>
> I am just trying to compare the speed with matlab. The arrange is used for 
> another test, that is why it shows up in the mail.

I think I don't get what you are after.  If you want to compare the speed
of code that *calculates* the same values it doesn't have to *look* the
same.  So what's the point of importing `numpy` and its `log` function if
you don't write the code in a fashion that takes advantage of the package
at all!?

And the other "pure" Python versions may gain some speed if you think
Python and not Matlab with Python syntax.  That might look like this:

from math import log

def bench42(n):
the_range = xrange(1, 1001)
for dummy in xrange(n):
for i in the_range:
z = [log(x) for x in xrange(i, i + 10)]
return z[-1]

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: pdb question - spew out "steps" until crash needed

2007-09-07 Thread Paul Rubin
James Stroud <[EMAIL PROTECTED]> writes:
> How do I get pdb to just run my program and spew out what's happening
> until it crashes/freezes? (This is a malloc error in a library
> somewhere and I can't figure out where--no exceptions thrown, etc.)

Maybe you want: http://docs.python.org/lib/module-trace.html

However, the malloc problem has probably already screwed things up
long before the application actually freezes.  Your best bet is
to recompile Python with malloc debugging enabled and/or run Python
itself under a debugger.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb: ValueError Something Stupid

2007-09-07 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, mcl
wrote:

> ValueError: invalid literal for int(): 0-

Could it be you have a MySQL column that is declared as some integer type,
but contains this funny "0-" value? So when MySQLdb tries to return it as a
Python integer, it fails to convert.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exponential float formmating

2007-09-07 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, 
[EMAIL PROTECTED] wrote:

> In all cases I need the number to start with 0
> 0.13000E+01

So why not move the decimal point left one, and add one to the exponent.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: platform system may be Windows or Microsoft since Vista

2007-09-07 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, 
[EMAIL PROTECTED] wrote:

> I'm thinking no priority because there is no fixing this.

Why are you bothering to check an informational string? Why not check
directly for the functionality you need?
-- 
http://mail.python.org/mailman/listinfo/python-list


pdb question - spew out "steps" until crash needed

2007-09-07 Thread James Stroud
How do I get pdb to just run my program and spew out what's happening 
until it crashes/freezes? (This is a malloc error in a library somewhere 
and I can't figure out where--no exceptions thrown, etc.)

I think I might need to live a lot longer to simply hit 's' [enter] 
until I get to the crash. Easiest would be run->spew->read last line.

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating a unique identifier

2007-09-07 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> > Sorry, make that 32 or 40 instead of 10, if the number of id's is large,
> > to make birthday collisions unlikely.
> 
> I did a small empirical test, and with 16 million ids, I found no 
> collisions.

16 million 32-byte ids?  With string and dictionary overhead that's
probably on the order of 1 GB.  Anyway, 16 bytes is enough, as
mentioned elsewhere.

> However, I did find that trying to dispose of a set of 16 million short 
> strings caused my Python session to lock up for twenty minutes until I 
> got fed up and killed the process. Should garbage-collecting 16 million 
> strings really take 20+ minutes?

Maybe your system was thrashing, or maybe the GC was happening during
allocation (there was some discussion of that a while back).

> > If you don't want the id's to be that large, you can implement a Feistel
> I'm not sure that I need it, but I would certainly be curious to see it.

I posted some code elsewhere in the thread.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exponential float formmating

2007-09-07 Thread Steven D'Aprano
On Fri, 07 Sep 2007 13:42:30 +, Marc 'BlackJack' Rintsch wrote:

> On Fri, 07 Sep 2007 06:08:19 -0700, zunbeltz wrote:
> 
>> For compatibility reasons with an old program I have to format string
>> in exponential format with the following format
>> 
>> 0.xE-yy
>> 
>> This means that the number start always by 0 and after the exponent
>> there should be alway the sing and 2 number for the exponent.
>> 
>> for example 13 shoud be 0.13000E+02
>> I always get 1.3E001
> 
> I don't know if this is platform dependent but this works for me:
> 
> In [41]: '%e' % 1.3
> Out[41]: '1.30e+00'
> 
> In [42]: ('%e' % 1.3).upper()
> Out[42]: '1.30E+00'

Alas, you've missed the Original Poster's requirement that the formatted 
number always starts with 0.

Also, an easier way to format floats with a capital E is to use %E 
instead of %e.

I don't believe there is a standard way of formatting floats with a 
leading zero.


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


Re: Generating a unique identifier

2007-09-07 Thread Steven D'Aprano
On Fri, 07 Sep 2007 19:17:44 -0700, Paul Rubin wrote:

>> Here's something which is a little less predictable than a straight
>> counter:
> 
> It's still very easy to generate valid id's from that, or guess the next
> one with non-negligible probability.

Well, in my specific application, the only consequences of guessing a 
valid id is that you get to congratulate yourself for guessing a valid 
id :)

As it turned out, I decided that since the only reason I had for avoiding 
consecutive ids was that they didn't look random, and that this would not 
really matter because no human being (including myself) was actually 
going to be looking at them except during debugging, I used the 
intertools.count() solution.


Thanks to all who replied.



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


Re: Python Problem

2007-09-07 Thread Carsten Haese
On Fri, 2007-09-07 at 21:58 -0400, Wiseman wrote:
> Hi,
> 
> The line:
> 
> import enchant
> 
> works perfectly OK when I call a Python progrma (sp.py) from IDLE
> (WInXP). When I try to run it ftom the command line (python sp.py) the
> response is:
> 
> Traceback (most recent call last):
>File "sp.py", line 3, in 
>  import enchant
> ImportError: No module named enchant

Enchant is a third-party package that must have been installed
separately. The most likely cause for the problem you're seeing is that
you have two Python versions on your computer, one with Enchant
installed, one without, and you're running the GUI of the one that does
have Enchant and the command line of the one that doesn't.

It's possible that the cause is something else, but to eliminate the
most obvious solution, run "import sys; print sys.version" in each
Python and check if they differ.

> Searching my computer (the whole of drive c:\) I could not find ANY
> file called enchant.*.

It is not necessary to have a file called enchant-dot-anything anywhere
on your disk to successfully import enchant as a module. The module
could also be built-in, stored inside a zip-file, or it could be a
package.

In enchant's case, it's a package, i.e. somewhere on your disk you'll
find a folder called "enchant" with a file "__init__.py" inside it.

To find out quickly where "enchant" is, simply issue "print enchant"
after importing enchant in IDLE. It'll tell you from where the module
was loaded.

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Generating a unique identifier

2007-09-07 Thread Steven D'Aprano
On Fri, 07 Sep 2007 08:47:58 -0700, Paul Rubin wrote:

> Paul Rubin  writes:
>> def unique_id():
>>return os.urandom(10).encode('hex')
> 
> Sorry, make that 32 or 40 instead of 10, if the number of id's is large,
> to make birthday collisions unlikely.

I did a small empirical test, and with 16 million ids, I found no 
collisions.

However, I did find that trying to dispose of a set of 16 million short 
strings caused my Python session to lock up for twenty minutes until I 
got fed up and killed the process. Should garbage-collecting 16 million 
strings really take 20+ minutes?


> If you don't want the id's to be that large, you can implement a Feistel
> cipher using md5 or sha as the round function pretty straightforwardly,
> then just feed successive integers through it. That also guarantees
> uniqueness, at least within one run of the program.  I have some sample
> code around for that, let me know if you need it.

I'm not sure that I need it, but I would certainly be curious to see it.


Thanks,


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


Re: Is a Borg rebellion possible? (a metaclass question)

2007-09-07 Thread BartlebyScrivener
On Sep 7, 1:53 pm, Steve Holden <[EMAIL PROTECTED]> wrote:

> All you really need is to create your SplinterBorgs with appropriate
> group names, you don't neef subclasses at all:

oops, I tried this once and the link broke. I'll try tinyurl.

Dang. With that subject heading I thought this was about some post-
Singularity, Python-programmed cyborgs rising up to take over the
universe.

See, e.g.
How To Survive A Robot Uprising
http://tinyurl.com/yrk5pw

I am officially misled!

rd


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


Re: Is a Borg rebellion possible? (a metaclass question)

2007-09-07 Thread BartlebyScrivener
On Sep 7, 1:53 pm, Steve Holden <[EMAIL PROTECTED]> wrote:

> All you really need is to create your SplinterBorgs with appropriate
> group names, you don't neef subclasses at all:
>

Dang. With that subject heading I thought this was about some post-
Singularity, Python-programmed cyborgs rising up to take over the
universe.

See, e.g.
http://www.amazon.com/How-Survive-Robot-Uprising-Defending/dp/
1582345929/inscape-20">How To Survive A Robot Uprising

I am officially misled!

rd

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


Re: subprocess.communicate messes things up

2007-09-07 Thread Gabriel Genellina
En Fri, 07 Sep 2007 22:51:34 -0300, <[EMAIL PROTECTED]> escribi�:

> problem is that the first time I press a key, it works, but after it
> just print the keys I press, the annoying line being the one with
> communicate, any idea of what is happening ?
>
>   child1 = subprocess.Popen("/usr/bin/mplayer -slave -quiet -
> idle",stdin=subprocess.PIPE,stdout=FNULL,stderr=FNULL,shell=True)
>   while 1:
>   ch=getkey()
>   name=os.listdir("/home/shivan/"+ch)
>   file_to_load = "/home/shivan/"+ch+"/"+name[0]
>   print "loadfile "+file_to_load
>   output, errors = child1.communicate("loadfile "+file_to_load+" 
> \n")

communicate sends its input and waits until the process finishes,  
collecting all output. So it's not adequate for your needs.
You should write directly to child1.stdin: child1.stdin.write("loadfile  
"+file_to_load+" \n")

-- 
Gabriel Genellina

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

Re: Subprocess module and unicode input

2007-09-07 Thread Gabriel Genellina
En Fri, 07 Sep 2007 18:46:26 -0300, Matthew Lausch <[EMAIL PROTECTED]>  
escribi�:

> I'd like to use the subprocess module with upper level characters in
> the process name or in the arguments to the process. Something like
> this:
>
> cmd = [ u'test_\u65e5\u672c\u8a9e_exec.bat', u'arg1', u'arg2' ]
> subprocess.call(cmd)
>
> But this gives the error:
>
> UnicodeEncodeError: 'ascii' codec can't encode characters in position
> 5-7: ordinal not in range(128)
>
> Is there a way around this problem? I don't want to assume any
> particular set of characters. The example above uses Japanese
> characters, but I would like to support anything.

You have to encode those unicode objects anyway - but you don't have to  
assume any encoding.
Your .bat file will be executed by CMD.EXE, and the shell expects a string  
- doesn't understand unicode objects. Like when you type that same  
commands on the console.
Use sys.getfilesystemencoding() to obtain the required encoding (likely  
"mbcs"):

fse = sys.getfilesystemencoding()
cmd = [arg.encode(fse) if isinstance(arg,unicode) else arg
for arg in cmd]

-- 
Gabriel Genellina

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

Re: Generating a unique identifier

2007-09-07 Thread Steve Holden
Paul Rubin wrote:
> Paul Rubin  writes:
>> the probability is about exp(-(2**60 / 2*2**160)) = 1/exp(2**101)
> 
> Bah.  Got that backwards and calculated wrong.  The probability of no
> collisions is
> 
> exp(-(2**60) / (2*2**160)) = exp(-(2**-101)) = approx (1 - 2**-101)
> 
> which is very close to 1.  The probability of collision is about
> 2**-101 which is close to 0.  Proofread first, then post.  I keep
> getting that in the wrong order. 

Right. The words "birthday attack" should have been in the back of your 
mind while you were writing that message.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Generating a unique identifier

2007-09-07 Thread Paul Rubin
Paul Rubin  writes:
> the probability is about exp(-(2**60 / 2*2**160)) = 1/exp(2**101)

Bah.  Got that backwards and calculated wrong.  The probability of no
collisions is

exp(-(2**60) / (2*2**160)) = exp(-(2**-101)) = approx (1 - 2**-101)

which is very close to 1.  The probability of collision is about
2**-101 which is close to 0.  Proofread first, then post.  I keep
getting that in the wrong order. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating a unique identifier

2007-09-07 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> > unique_id = itertools.count(1234567890)
> 
> Sweet!
> 
> I really must make itertools second-nature. I always forget it.

Beware that count() output (like enumerate) is always <= sys.maxint.
It raises an exception if it overflows.  IMO this is a bug.

> > def unique_id():
> >return os.urandom(10).encode('hex')
> 
> Any time I see something using a random number to generate IDs, I worry 
> about collisions. Am I being paranoid? (But even paranoids write code 
> with bugs...)

Well, the idea is to make the string long enough (I shouldn't have
picked 10 bytes) to make the probability of collisions acceptably low.
The probability is about exp(-k**2/(2*N)) where k is the number of
id's you use and N is the number of possible ID's.  So with
os.urandom(20), if you use 1 billion (= approx 2**30) id's, 
the probability is about exp(-(2**60 / 2*2**160)) = 1/exp(2**101)
which is extremely small.  Using random strings is probably safer
from collisions than maintain keep distinct initial counters
across multiple runs of a program, on multiple computers, etc.

The classic example is ethernet cards.  Each one is supposed to have a
unique hardware 48-bit MAC address, with routers etc. relying on the
uniqueness.  Some organization is supposed to assign a unique code to
each manufacturer, and then the manufacturer uses that code as a
prefix and assigns addresses in sequence within that space.  That
works fine until sales go up, manufacturers start opening multiple
factories operating out of the same space, low-rent manufacturers
start making up their own codes, etc.  So companies that buy large
numbers of cards often find multiple cards with the same address,
causing various hassles.  If they just assigned 128-bit MAC addresses
at random it's very unlikely that there would ever be a collision.

> Here's something which is a little less predictable than a straight 
> counter:

It's still very easy to generate valid id's from that, or guess the
next one with non-negligible probability.  IMO it's almost never worth
messing with a "little less predictable".  If you're trying to prevent
an actual opponent from guessing something, use full-strength
cryptography.

You could try something like this:

import sha, os, itertools

radix = 2**32   # keep this == 2**(some even number <= 80)
secret_key = os.urandom(20)

def prp(key, n):
   # pseudo-random permutation (8-round Feistel network)
   # transform n to a unique number < radix**2
   assert 0 <= n < radix**2

   def F(i,x):
 return int(sha.new('%s,%x,%x'%(key,i,x)).hexdigest(), 16) % radix

   a,b = divmod(n, radix)
   for i in xrange(8):
 a ^= F(i,b)
 a,b = b,a   
   return radix*a + b

unique_id = (prp(secret_key, i) for i in itertools.count())

It should be pretty secure and (unless I made an error) is a 
permutation from [0:radix**2] to [0:radix**2], similar to DES.
It's invertible if you know the secret key (I'll leave that as an
exercise).  8 rounds is probably overkill for radix 2**32.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking if elements are empty

2007-09-07 Thread Wildemar Wildenburger
Lawrence D'Oliveiro wrote:
 if y[0]:
>>> Not a good idea.
>> Why not?
> 
> Because there is a situation where your version of the test will fail even
> if the first element of y is non-null.

Such as? Seriously people, a little more verbosity wouldn't hurt here. 
This isn't a mystery game.

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


Python Problem

2007-09-07 Thread Wiseman
Hi,

The line:

import enchant

works perfectly OK when I call a Python progrma (sp.py) from IDLE
(WInXP). When I try to run it ftom the command line (python sp.py) the
response is:

Traceback (most recent call last):
   File "sp.py", line 3, in 
 import enchant
ImportError: No module named enchant

Searching my computer (the whole of drive c:\) I could not find ANY
file called enchant.*.

Does anyone know what is wrong?

Thanks

((:-()  Meir


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


subprocess.communicate messes things up

2007-09-07 Thread KingShivan
please could you take a look at this piece of code ?

what I'd like is typically a sound boc : press one key, and get the
associated sound.
for this I place the sound files in different directories (easy to
move and modify) and when a key is pressed I grab the first file of
the corresponding directory.

problem is that the first time I press a key, it works, but after it
just print the keys I press, the annoying line being the one with
communicate, any idea of what is happening ?

thank you for reading

import os,subprocess, tty, termios,sys,time
FNULL = open('/dev/null', 'w')
def getkey():
file = sys.stdin.fileno()
mode = termios.tcgetattr(file)
try:
tty.setraw(file, termios.TCSANOW)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(file, termios.TCSANOW, mode)
return ch

def main():
child1 = subprocess.Popen("/usr/bin/mplayer -slave -quiet -
idle",stdin=subprocess.PIPE,stdout=FNULL,stderr=FNULL,shell=True)
while 1:
ch=getkey()
name=os.listdir("/home/shivan/"+ch)
file_to_load = "/home/shivan/"+ch+"/"+name[0]
print "loadfile "+file_to_load
output, errors = child1.communicate("loadfile "+file_to_load+" 
\n")



main()

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


Re: Generating a unique identifier

2007-09-07 Thread Paul Rubin
Ben Finney <[EMAIL PROTECTED]> writes:
> > http://docs.python.org/lib/module-uuid.html
> I second this recommendation. If you want arbitrary unique IDs that
> are not a function of the data they identify, the simplest solution is
> a monotonically-increasing serial number. If you want more than that,
> you might as well go straight to the standard UUIDs.

The standard UUID's as described in that url don't make any serious
attempt to be unguessable.  It's better to use a string from os.urandom().

To Stephen: double oops, I was thinking of hex digits rather than bytes
when I suggested reading 32 (length of an md5 hash) or 40 (length of
an sha1 hash) from os.urandom.  That should have said 16 or 20 bytes.

If k is the number of unique id's you'll actually use, and N is the
number of possible random uid's (so for 16 bytes, N=2**128 since
16 bytes is 128 bits), the probability of a collision occuring is
approximately exp(-k**2 / (2*N)), assuming k is small compared
with sqrt(N).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating a unique identifier

2007-09-07 Thread Steven D'Aprano
On Fri, 07 Sep 2007 08:42:45 -0700, Paul Rubin wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> writes:
>> def unique_id():
>> n = 1234567890
>> while True:
>> yield n
>> n += 1
> 
> unique_id = itertools.count(1234567890)

Sweet!

I really must make itertools second-nature. I always forget it.

 
>> which is easy enough, but I thought I'd check if there was an existing
>> solution in the standard library that I missed. Also, for other
>> applications, I might want them to be rather less predictable.
> 
> def unique_id():
>return os.urandom(10).encode('hex')

Any time I see something using a random number to generate IDs, I worry 
about collisions. Am I being paranoid? (But even paranoids write code 
with bugs...)


Here's something which is a little less predictable than a straight 
counter:

def unpredictable_counter(n=12345678):
while True:
n += random.randint(1, 68)
yield n

def more_unpredictable_counter(n=1234567):
uc = unpredictable_counter(n)
pool = []
while True:
if not pool:
pool = [None]*99
for i in range(99):
pool[i] = uc.next()
random.shuffle(pool)
yield pool.pop()




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


Re: creating really big lists

2007-09-07 Thread Gabriel Genellina
En Fri, 07 Sep 2007 16:16:46 -0300, Dr Mephesto <[EMAIL PROTECTED]>  
escribi�:

> hey, that defaultdict thing looks pretty cool...
>
> whats the overhead like for using a dictionary in python?

Dictionaries are heavily optimized in Python. Access time is O(1),  
adding/removing elements is amortized O(1) (that is, constant time unless  
it has to grow/shrink some internal structures.)

-- 
Gabriel Genellina

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

Re: Best way to do attribute docstrings?

2007-09-07 Thread Gabriel Genellina
En Fri, 07 Sep 2007 17:06:07 -0300, Ken Kuhlman <[EMAIL PROTECTED]>  
escribi�:

> What's the best method for annotating attributes with a docstring?
> I'm looking to be able to introspect my class & get the comments back
> out.

I don't know which is the *best* method. Perhaps you might use properties  
instead. Or some kind of convention, like
four_legs__doc__ = "Animal has four legs"
to be the docstring associate to `four_legs` attribute.

> The technique I'm using is a little hoaky, but works.. basically I
> create subclasses of the builtin types that I want to be able to use &
> then instantiate them in my attribute assignments.   This gives me an
> object that I can tweak the __doc__ attribute on.   An example of what
> my code looks like is included below.

I don't like subclassing builtins, it doesn't work in general. _("Hello")  
+ _(" world!") is a plain str object, not your derived class.
What about instance attributes? All your examples show class attributes.  
Your docstring appears to be attached to the attribute "value", but it  
should be attached to the attribute definition, or be a class attribute,  
or something like that, shared between all instances and somewhat  
permanent. Else, reassigning the attribute will lose the docstring.

> # Boolean gave me extra fits that I don't understand, but this
> technique works
> class MyBool(int):
> def __str__(self):
> return `self.__int__() > 0`
> def __repr__(self):
> return self.__str__()

Let Python do the boolean conversion: -1 is a true value, but MyBool(-1)  
would say False.
I don't understand exactly why do you want this class, but I'd write it  
this way:

class MyBool(int):
 def __str__(self):
 return str(bool(self))
 __repr__ = __str__

> def bool_func(val):
> def blah():
>return MyBool(val)
> return blah
> true = bool_func(True)
> false = bool_func(False)

And why do you need such functions?

-- 
Gabriel Genellina

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

Re: How to determine the bool between the strings and ints?

2007-09-07 Thread Steven D'Aprano
On Fri, 07 Sep 2007 17:40:44 +0200, Jorgen Bodde wrote:

> is the bool derived from 'int' in some way? 

Yes.

>>> issubclass(bool, int)
True


> What is the best way to
> check if the config I want to write is an int or a bool ?

if isinstance(value, bool):
print "it's a bool, or a subclass of bool"
elif isinstance(value, int):
print "it's an int, or a subclass of int other than bool"



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


Re: Is a Borg rebellion possible? (a metaclass question)

2007-09-07 Thread Carsten Haese
On Fri, 2007-09-07 at 14:54 -0600, Steven Bethard wrote:
> Carsten Haese wrote:
> > [slightly convoluted example...]
> 
> I think I would probably write that as::
> [concise example...]
> 
> That is, I don't think there's really a need for __new__ if you're using 
> a metaclass. Just set the instance's __dict__ in the __call__ method of 
> the metaclass.

Good point. I suppose it shows that this is the first metaclass I've
ever written, but it works, and it didn't make my brain explode ;)

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Speed of Python

2007-09-07 Thread Carl Banks
On Sep 7, 12:42 pm, "wang frank" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> While comparing the speed of octave and matlab, I decided to do a similar
> test for python and matlab. The result shows that python is slower than
> matlab by a factor of 5. It is not bad since octave is about 30 time slower
> than matlab.
>
> Here is the result in matlab:
> Elapsed time is 0.015389 seconds.
>
> and in Python:>>> t=timeit.Timer("bench1.bench1(10)","import bench1")
> >>> t.repeat(1,1)
>
> [0.071012377266015392]
>
> Here is the bench1.py:
> import math
> def bench1(n):
> for i in range(n):
> for j in range(1000):
> m=j+1
> z=math.log(m)
> z1=math.log(m+1)
> z2=math.log(m+2)
> z3=math.log(m+3)
> z4=math.log(m+4)
> z5=math.log(m+5)
> z6=math.log(m+6)
> z7=math.log(m+7)
> z8=math.log(m+8)
> z9=math.log(m+9)
> return z9
>
> Is my conclusion correct that Python is slower than matlab?


Whoa, there, chief, that's a pretty lofty conclusion to make based on
one benchmark.

A blanket speed comparison between Matlab and Python isn't productive:
they each have their own strengths speedwise.

(Conversely, a blanket comparison is productive programmingwise.
Matlab has almost no strengths relative to Python in that department.
But that's another question entirely. :)

Roughly speaking, I'd say your average single-pass calculation script
is going to be faster in Matlab than in Python.  However, Python (with
help from numpy) has more opportunities for optimization, especially
if you're using large matrices.  And if you need to take it up a
notch, Python has very good ways to integrate numerical C and Fortran
code.


> Are there any
> way to speed it up? It seems Python automatically created bench1.pyc. Does
> Python automatically execute the bench1.pyc to speed it up?

Yes, as others have explained.


Carl Banks

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

Re: application version checking against database

2007-09-07 Thread Gabriel Genellina
En Fri, 07 Sep 2007 10:12:09 -0300, Hamilton, William   
<[EMAIL PROTECTED]> escribi�:

>> We are trying to implement a system that checks the version of the
>> application against a version number stored in the database.  We don't
>> want the app and the db don't become out of sync.
>>
>> We have tried setting a __version__ variable in the top most module,
>> however, it seems that this is not accessible for the modules that are
>> subsequently imported.  There are a several locations in the app where
>> we want to do the version check, but we would like to have one place
>> to set the version number, namely the top level module.
>
> You could add a Version module that contains the version number and any
> functions related to the version checking, and import that into the
> modules that do version checking.

Also, there is a version module already available from the standard  
library:

 from distutils.version import StrictVersion
__version__ = StrictVersion("1.3")
__version__ = '$Revision: 1.19 $'[11:-2]

The last line is for CVS.

-- 
Gabriel Genellina

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

Re: Speed of Python

2007-09-07 Thread Terry Reedy

"wang frank" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|z=log(j);

This matlab code is faster in part than your Python equivalent:

| > > z=math.log(m)

because of the repeated lookup of log in the math module.
So, replace

| > > import math

with

from math import log

Also make that the top line of the function so 'log' is a local variable. 
Then delete 'math.' everywhere.

That said, such artificial benchmarks do not strike me as terribly useful. 
More useful, for instance, for appropriate applications, might be doing a 
fourier transform on a 2**20 length vector with both matlab and numpy/scipy

tjr



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


Re: Best practice prompting for password

2007-09-07 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, GiBo wrote:

> what's the best practice to securely prompt user for password on console
> in Python? IIRC some programs like SSH do a lot to ensure that the input
> comes from TTY and is not redirected from somewhere and several other
> checks.

Does it? Why bother?

It's not where the password comes _from_ that you have to be careful about,
it's what you do with it after you get it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking if elements are empty

2007-09-07 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Wildemar
Wildenburger wrote:

> Lawrence D'Oliveiro wrote:
>
>> In message <[EMAIL PROTECTED]>, Chris
>> Mellon wrote:
>> 
>>> On 9/5/07, Steve Holden <[EMAIL PROTECTED]> wrote:
 Doran, Harold wrote:
>
> Is there a way to check if the first element of y is null?
> 
 len(y[0]) == 0

>>> Better spelled as
>>>
>>> if y[0]:
>> 
>> Not a good idea.
> 
> Why not?

Because there is a situation where your version of the test will fail even
if the first element of y is non-null.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unexpected behavior: did i create a pointer?

2007-09-07 Thread Steven D'Aprano
On Fri, 07 Sep 2007 15:59:53 +0200, Wildemar Wildenburger wrote:

> I just thought I'd go along with the analogy the OP created as that was
> his mindset and it would make things easier to follow if I didn't try to
> forcibly change that.

My reaction to somebody trying to reason with the wrong analogy is to 
teach them the right analogy, not to tell them they got it right when 
they actually got it wrong.

"My car won't start -- I must not have stirred the gasoline enough before 
baking it."

"Yes, that's right. It's very important to stir the gasoline fully so 
that all the ingredients are fully mixed."


-- 
Steven.

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


Re: Speed of Python

2007-09-07 Thread wang frank
I am just trying to compare the speed with matlab. The arrange is used for 
another test, that is why it shows up in the mail.


Thanks

Frank



From: "Marc 'BlackJack' Rintsch" <[EMAIL PROTECTED]>
To: python-list@python.org
Subject: Re: Speed of Python
Date: 7 Sep 2007 23:17:55 GMT

On Fri, 07 Sep 2007 22:59:26 +, wang frank wrote:

> I also have tried to use numpy to speed it up. However, surprisingly, 

it is

> slower than the pure python code.
>
> Here is the code:
> import  numpy
> arange=numpy.arange
> nlog=numpy.log
> def bench6(n):
>for i in xrange(n):
>for j in xrange(1000):
>m=j+1
>z=nlog(m)
>z1=nlog(m+1)
>z2=nlog(m+2)
>z3=nlog(m+3)
>z4=nlog(m+4)
>z5=nlog(m+5)
>z6=nlog(m+6)
>z7=nlog(m+7)
>z8=nlog(m+8)
>z9=nlog(m+9)
>return z9
>
> [窶ヲ]
>
> Anyone know why?

Because you don't really take advantage of `numpy`.  The `numpy.log()`
function can be used with scalars but I guess it is slower because it has
to check if its argument is a scalar or array.  Untested:

from numpy import arange, log as nlog

def bench6(n):
for dummy in xrange(n):
for j in xrange(1000):
z = nlog(arange(j + 1, j + 11))
return z[-1]
--
http://mail.python.org/mailman/listinfo/python-list


_
3つの”ホンモノ”プレゼント 賞品第3弾スタート!アルファ スパイダー2.2が当た
る http://clk.atdmt.com/GBL/go/msnjpqjl006010gbl/direct/01/ 

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

Re: Generating a unique identifier

2007-09-07 Thread Ben Finney
Will Maier <[EMAIL PROTECTED]> writes:

> On Fri, Sep 07, 2007 at 12:03:23PM -, Steven D'Aprano wrote:
> [...]
> > which is easy enough, but I thought I'd check if there was an
> > existing solution in the standard library that I missed. Also, for
> > other applications, I might want them to be rather less
> > predictable.
> 
> 2.5 includes the uuid module for RFC 4122 universally-unique IDs:
> 
> http://docs.python.org/lib/module-uuid.html

I second this recommendation. If you want arbitrary unique IDs that
are not a function of the data they identify, the simplest solution is
a monotonically-increasing serial number. If you want more than that,
you might as well go straight to the standard UUIDs.

Even if you're not using Python 2.5, grab the external 'python-uuid'
package for your operating system and use that. If you use the options
for including random elements, the generated UUIDs will even satisfy
your "unpredictable" requirement.

-- 
 \  "This sentence contradicts itself -- no actually it doesn't."  |
  `\ -- Douglas Hofstadter |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Speed of Python

2007-09-07 Thread Marc 'BlackJack' Rintsch
On Fri, 07 Sep 2007 22:59:26 +, wang frank wrote:

> I also have tried to use numpy to speed it up. However, surprisingly, it is 
> slower than the pure python code.
> 
> Here is the code:
> import  numpy 
> arange=numpy.arange
> nlog=numpy.log
> def bench6(n):
>   for i in xrange(n):
>   for j in xrange(1000):
>   m=j+1
>   z=nlog(m)
>   z1=nlog(m+1)
>   z2=nlog(m+2)
>   z3=nlog(m+3)
>   z4=nlog(m+4)
>   z5=nlog(m+5)
>   z6=nlog(m+6)
>   z7=nlog(m+7)
>   z8=nlog(m+8)
>   z9=nlog(m+9)
>   return z9   
> 
> […]
> 
> Anyone know why?

Because you don't really take advantage of `numpy`.  The `numpy.log()`
function can be used with scalars but I guess it is slower because it has
to check if its argument is a scalar or array.  Untested:

from numpy import arange, log as nlog

def bench6(n):
for dummy in xrange(n):
for j in xrange(1000):
z = nlog(arange(j + 1, j + 11))
return z[-1]
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: why should I learn python

2007-09-07 Thread 7stud
On Sep 6, 10:51 pm, James Stroud <[EMAIL PROTECTED]> wrote:
> BartlebyScrivener wrote:
> > On Sep 6, 5:36 pm, André <[EMAIL PROTECTED]> wrote:
>
> >> Easy to read, easy to write, good libraries and, I have found, an
> >> extremely helpful community.
>
> >> Hobbyists (like me) can work on projects written in Python on and off
> >> (sometimes for weeks if not months without programming) and be able to
> >> resume the work very quickly (because it's so easy to read and
> >> understand the code).
>
> > I second these.  I am not a programmer. You can get busy with other
> > projects for weeks and come back to Python code and pick up where you
> > left off, because it uses WORDS.  Try remembering what (<>) or <*>
> > means after being away from Perl for a month.
>
> > rd
>
> Better is to try to remember the differences between and uses of:
>
>$stupidPerl[4]
>${stupidPerl}[4]
>$stupidPerl->[4]
>${stupidPerl}->[4]
>$#stupidPerl[4]
>$#{stupidPerl}[4]
>$#{stupidPerl}->[4]
>$#{$stupidPerl}->[4]->[4]
>
> And so on.
>
> Quiz: which are valid? (Careful now.)
>
> The friggin' language is useless (except for the fact that, like
> window$, a lot of people insist on using it over superior alternatives
> and so you find yourself confronting it from time to time). In fact, it
> was the need to use nested data structures that made me move to python
> when I realized all of the above would be a thing of the past (also made
> useless my perl "cheat sheet" that sits in my big-fat-useless-camel-book).
>
> $Perl->[Useless]
>
> --
> James Stroud
> UCLA-DOE Institute for Genomics and Proteomics
> Box 951570
> Los Angeles, CA 90095
>
> http://www.jamesstroud.com/

rofl.

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

Re: why should I learn python

2007-09-07 Thread 7stud
On Sep 6, 9:20 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Thu, 06 Sep 2007 23:34:10 -0300, Grant Edwards <[EMAIL PROTECTED]>  
> escribi?:
>
> > On 2007-09-06, Torsten Bronger <[EMAIL PROTECTED]> wrote:
> >> Hallöchen!
>
> >> Tom Brown writes:
>
> >>> [...] Python has been by far the easiest to develop in.  Some
> >>> people might say it is not "real programming" because it is so
> >>> easy.
>
> >> I can't believe this.  Have you really heard such a statement?
>
> > Maybe it's a allusion to that fake Stroustrup interview where
> > he supposedly explains that C++ was meant to be a difficult
> > language to use as a means to keep more programmers employed at
> > higher salaries?
>
> I always thought the only goal of the C++ standard comittee was to devise  
> the most intrincate and convoluted rule ever imaginable.
> It's like playing AD&D: the basic manual says something, but The Book Of  
> The Perfect And Sublime Elf says that in this case this other rule  
> applies, but a warrior Elf can read in The Ultimate And Most Complete  
> Warrior Companion a totally different rule, but the character's alignment  
> forbids all the three possibilities...
>
> --
> Gabriel Genellina

Ha, ha, ha!  lol. :)

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

Re: What does this thread have to do with classical music,

2007-09-07 Thread ah
Art Deco wrote:
> ah <[EMAIL PROTECTED]> wrote:
>>Art Deco wrote:
>>> ah <[EMAIL PROTECTED]> wrote:
Art Deco wrote:
> ah <[EMAIL PROTECTED]> wrote:
>>Art Deco wrote:
>>> ah <[EMAIL PROTECTED]> wrote:
Art Deco wrote:
> ah <[EMAIL PROTECTED]> wrote:
>>Art Deco wrote:
>>> ah <[EMAIL PROTECTED]> wrote:
Art Deco wrote:
> Who wrote?
> 
> 
>>What does that have to do with classical music, snuhwolf?
> 
>>What does that have to do with classical music, snuhwolf?
> 
> How many more times will you be asking the same tired, lame
> questions,
> Tholen?

Till 2056?
>>> 
>>> At that point, he will have made the Thirty Years Pset War look like
>>> 1967 in the Sinai.
>>
>>It must have been Hell to keep a garden during those times.
>>
>>Did they all eat jerky, or what?
> 
> Worse -- worm-laden hardtack.

Luxury!

Why, I remember when I was a lad . . . we used to watch the local churls
across the fences eating that well.

We only had millings (and (occasionally) water) on Tuesdays and Fridays.
>>> 
>>> Grog and hardtack, life is good!
>>
>>¡Viva la basura!
> 
> Vivat les ordures!

Vivara los trunctiato!
>>> 
>>> das Leben ist gut!
>>
>>de Handel esta disgustipado!
> 
> la vita è buona!

que grupo da merda!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Speed of Python

2007-09-07 Thread wang frank


I also have tried to use numpy to speed it up. However, surprisingly, it is 
slower than the pure python code.


Here is the code:
import  numpy 
arange=numpy.arange

nlog=numpy.log
def bench6(n):
for i in xrange(n):
for j in xrange(1000):
m=j+1
z=nlog(m)
z1=nlog(m+1)
z2=nlog(m+2)
z3=nlog(m+3)
z4=nlog(m+4)
z5=nlog(m+5)
z6=nlog(m+6)
z7=nlog(m+7)
z8=nlog(m+8)
z9=nlog(m+9)
return z9   

from math import log
def bench3(n):
for i in xrange(n):
for j in xrange(1000):
#   m=j+1
z=log(j+1)
z1=log(j+2)
z2=log(j+3)
z3=log(j+4)
z4=log(j+5)
z5=log(j+6)
z6=log(j+7)
z7=log(j+8)
z8=log(j+9)
z9=log(j+10)
return z9   

Here is the result:


t6=timeit.Timer("bench1.bench6(10)", "import bench1")
t6.repeat(1,1)

[0.73878858905254674]

t3=timeit.Timer("bench1.bench3(10)", "import bench1")
t3.repeat(1,1)

[0.056632337350038142]


Anyone know why?

Thanks

Frank



From: "Kurt Smith" <[EMAIL PROTECTED]>
To: "wang frank" <[EMAIL PROTECTED]>
Subject: Re: Speed of Python
Date: Fri, 7 Sep 2007 16:49:05 -0500

On 9/7/07, wang frank <[EMAIL PROTECTED]> wrote:
> Hi,
> Here is the matlab code:
> function [z]=bench1(n)
> for i=1:n,
> for j=1:1000,
> z=log(j);
> z1=log(j+1);
> z2=log(j+2);
> z3=log(j+3);
> z4=log(j+4);
> z5=log(j+5);
> z6=log(j+6);
> z7=log(j+7);
> z8=log(j+8);
> z9=log(j+9);
> end
> end
> z = z9;
>
> I am not familiar with python, so I just simply try to reproduce the 

same

> code in python.
> If you think that my python script is not efficient, could you tell me 

how

> to make it more efficient?

One thing you can do is bind math.log to the function's namespace thusly:

import math
def bench1_opt(n):
log = math.log
for i in range(n):
for j in range(1000):
m=j+1
z=log(m)
z1=log(m+1)
z2=log(m+2)
z3=log(m+3)
z4=log(m+4)
z5=log(m+5)
z6=log(m+6)
z7=log(m+7)
z8=log(m+8)
z9=log(m+9)
return z9

On my system I get about a 20% speedup over the 'unoptimized' version
(even though this optimization is rather trivial and may even help
readability).  Still not matlab speed, but better.  You might be able
to do better using xrange instead of range, but the loop overhead
isn't the main slowdown (only about 1% ).

For comparisons in real-world usage (if you are doing numerical work),
I urge you to take a look at a specifically numerical package --
numpy/scipy or their equivalents: http://www.scipy.org/  Python is a
*very* general language not suited for heavy numerical work out of the
box -- dedicated numerical packages adapt python to this specialized
envirornment, and are becoming more and more competitive with Matlab.
The best part is you can put your time-critical code in FORTRAN or C
and wrap it with pyrex, f2py, weave, etc. pretty easily, and still
have the beauty of Python gluing everything together.

Kurt


_
メッセンジャー用アイコンに大人気オンラインゲームの萌えなキャラが登場! 
http://messenger.live.jp/ 

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

Re: why should I learn python

2007-09-07 Thread Ricardo Aráoz
Tom Brown wrote:
> On Thursday 06 September 2007 15:44, Torsten Bronger wrote:
>> Hallöchen!
>>
>> Tom Brown writes:
>>> [...] Python has been by far the easiest to develop in.  Some
>>> people might say it is not "real programming" because it is so
>>> easy.
>> I can't believe this.  Have you really heard such a statement?
> 
> Yes. I was told this by a C programmer. Something about doing it all yourself 
> and not using provided packages. I countered with something about reinventing 
> the wheel. :)
> 

You should have asked if he used the OS or did he control the devices
(HD, screen) himself.


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


Re: Finding specific date ranges

2007-09-07 Thread Ricardo Aráoz
Tim Golden wrote:
> [EMAIL PROTECTED] wrote:
>> Hi,
>>
>> I am working on a timesheet application in which I need to to find the
>> first pay period in a month that is entirely contained in that month
>> to calculate vacation time. Below are some example date ranges:
>>
>>
>> December 31, 2006January 13, 2007 # doesn't earn
>> January 14, 2007 January 27, 2007 # does earn
>> January 28, 2007 February 10, 2007 # doesn't
>> February 11, 2007February 24, 2007 # does
>>

What about (untested) :
import datetime

def itEarns(fromDate, toDate) :
return (fromDate.year == toDate.year and fromDate.month == toDate.month)

periods = [
(datetime.date(2006, 12, 31), datetime.date(2007, 1, 13)),
(datetime.date(2007, 1, 14), datetime.date(2007, 1, 27)),
(datetime.date(2007, 1, 28), datetime.date(2007, 2, 10)),
(datetime.date(2007, 2, 11), datetime.date(2007, 2, 24))
]

candidatePeriods = [(frm, to) for frm, to in periods if itEarns(frm, to)]

??

>>
>> So far, the best approach I've come up with is to create a list of
>> tuples that contain the pay period date ranges for the year and
>> iterate through the tuples looking for the first occurrence of the
>> month names matching. Then I'd add that date range to a separate list
>> and somehow ignore any other matches in that month. This seems like a
>> hack. Does anyone have a better idea?
> 
> 
> Well, I can come up with a solution which basically reflects the
> way I'd do it in SQL (since this kind of thing is my bread-and-butter
> there) but I'm not convinced it's really any better than your proposal.
> However, for the purposes of illustration:
> 
> 
> import calendar
> import datetime
> 
> YEAR = 2007
> 
> months = [
>(datetime.date (YEAR, n, 1), datetime.date (YEAR, n, calendar.monthrange 
> (YEAR, n)[1]))
>for n in range (1, 13)
> ]
> 
> periods = [
>(datetime.date(2006, 12, 31), datetime.date(2007, 1, 13)),
>(datetime.date(2007, 1, 14), datetime.date(2007, 1, 27)),
>(datetime.date(2007, 1, 28), datetime.date(2007, 2, 10)),
>(datetime.date(2007, 2, 11), datetime.date(2007, 2, 24))
> ]
> 
> for m in months:
>candidate_periods = [p for p in periods if m[0] <= p[0] and p[1] <= m[1]]
>if candidate_periods:
>  print m[0], "=>", min (candidate_periods)
>else:
>  print m[0], "=>", "no period matches"
> 
> 
> 
> TJG


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


Subprocess module and unicode input

2007-09-07 Thread Matthew Lausch
I'd like to use the subprocess module with upper level characters in
the process name or in the arguments to the process. Something like
this:

cmd = [ u'test_\u65e5\u672c\u8a9e_exec.bat', u'arg1', u'arg2' ]
subprocess.call(cmd)

But this gives the error:

UnicodeEncodeError: 'ascii' codec can't encode characters in position
5-7: ordinal not in range(128)

Is there a way around this problem? I don't want to assume any
particular set of characters. The example above uses Japanese
characters, but I would like to support anything.

Thanks.

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


Re: How to convert None to null value

2007-09-07 Thread Steve Holden
Carsten Haese wrote:
> On Fri, 2007-09-07 at 12:10 -0700, Dennis Lee Bieber wrote:
>> On Fri, 07 Sep 2007 09:07:49 -0400, Carsten Haese <[EMAIL PROTECTED]>
>> declaimed the following in comp.lang.python:
>>
>>
>>> doesn't have a parameter binding mechanism, you should throw it away and
>>> replace it with a DB-API complaint module.
>>>
>>  I hadn't realized the DB-API defined a "complaint" module 
> 
> Yeah, I noticed the typo a minute too late. Dyslexics of the world,
> untie! ;-)
> 
Dyslexia rules, KO

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Is a Borg rebellion possible? (a metaclass question)

2007-09-07 Thread Steven Bethard
Carsten Haese wrote:
> Indeed, if you have an __init__ method that shouldn't see the "group"
> argument, you need a metaclass after all so you can yank the "group"
> argument between __new__ and __init__. The following code seems to work,
> but it's making my brain hurt:
> 
> class SplinterBorgMeta(type):
> def __call__(cls, *args, **kwargs):
> inst = cls.__new__(cls, *args, **kwargs)
> kwargs.pop("group",None)
> inst.__init__(*args,**kwargs)
> return inst
> 
> class SplinterBorg(object):
> __metaclass__ = SplinterBorgMeta
> _shared_states = {}
> def __new__(cls, *a, **k):
> group = k.pop("group","BORG")
> obj = object.__new__(cls, *a, **k)
> obj.__dict__ = cls._shared_states.setdefault(group,{})
> return obj
> 
> class MyClass(SplinterBorg):
> def __init__(self, name):
>self.name = name
> 

I think I would probably write that as::

 >>> class SplinterBorgMeta(type):
 ... def __init__(cls, name, bases, bodydict):
 ... cls._shared_states = {}
 ... def __call__(cls, *args, **kwargs):
 ... group = kwargs.pop('group', None)
 ... inst = cls.__new__(cls, *args, **kwargs)
 ... inst.__dict__ = cls._shared_states.setdefault(group, {})
 ... inst.__init__(*args, **kwargs)
 ... return inst
 ...
 >>> class MyClass(object):
 ... __metaclass__ = SplinterBorgMeta
 ... def __init__(self, name):
 ... self.name = name
 ...
 >>> a = MyClass('a')
 >>> aa = MyClass('aa')
 >>> b = MyClass('b', group='b')
 >>> bb = MyClass('bb', group='b')
 >>> a.name, aa.name, b.name, bb.name
 ('aa', 'aa', 'bb', 'bb')

That is, I don't think there's really a need for __new__ if you're using 
a metaclass. Just set the instance's __dict__ in the __call__ method of 
the metaclass.

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


Re: Python and Cron

2007-09-07 Thread Shawn Milochik
Any chance your import statements aren't coming in properly due to
something in your environment in Python that's not being inherited by
your cron job?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Speed of Python

2007-09-07 Thread wang frank

Thanks for all your help.

Using Istvan Albert's suggestion, I have recompared the speed of the 
following funciton:

matlab:
function [z]=bench2(n)
for i=1:n,
   j=(0:999);
   z=log(j+1);
end 


python:
from  numpy import arange, log
def bench4(n):
   for i in xrange(n):
   nums = arange( n )
   a = log( nums + 1)

Python actually is faster than Matlab.

tic; z=bench2(1000); toc
Elapsed time is 0.159485 seconds.

Python:

import timeit
t=timeit.Timer("bench1.bench4(1000)","import bench1")
t.repeat(1,1)

[0.10052953657517924]

Thanks again.

Frank

From: ajaksu <[EMAIL PROTECTED]>
To: python-list@python.org
Subject: Re: Speed of Python
Date: Fri, 07 Sep 2007 19:27:45 -

On Sep 7, 2:37 pm, "wang frank" <[EMAIL PROTECTED]> wrote:
> I am not familiar with python, so I just simply try to reproduce the 

same

> code in python.
Seems almost correct, but from what I guess of MatLab, George's
suggestions make it a bit more fair.

> If you think that my python script is not efficient, could you tell me 

how

> to make it more efficient?
In pure Python? No idea (besides using Roberto's and George's
suggestions). If you allow for extensions, Istvan has the answer. If
you allow compiling Python to C++ (using ShedSkin: 

http://shed-skin.blogspot.com/),

here's a small report:

--
[EMAIL PROTECTED]:~/sandbox$ cat bench.py
import math
n = 1
def bench1(n):
for i in range(n):
for j in range(1000):
m=j+1
z=math.log(m)
z1=math.log(m+1)
z2=math.log(m+2)
z3=math.log(m+3)
z4=math.log(m+4)
z5=math.log(m+5)
z6=math.log(m+6)
z7=math.log(m+7)
z8=math.log(m+8)
z9=math.log(m+9)
return z9
a = bench1(10)

[EMAIL PROTECTED]:~/sandbox$ ss -e bench.py
*** SHED SKIN Python-to-C++ Compiler 0.0.22 ***
Copyright 2005-2007 Mark Dufour; License GNU GPL version 2 (See
LICENSE)
(Please send bug reports here: [EMAIL PROTECTED])

[iterative type analysis..]
**
iterations: 2 templates: 44
[generating c++ code..]
[EMAIL PROTECTED]:~/sandbox$ make bench.so
g++  -O3 -s -pipe -fomit-frame-pointer  -I/home/ajaksu/shedskin-0.0.22/
lib -g -fPIC -I/usr/include/python2.5 -D__SS_BIND /home/ajaksu/
shedskin-0.0.22/lib/builtin.cpp /home/ajaksu/shedskin-0.0.22/lib/
math.cpp bench.cpp -lgc  -shared -Xlinker -export-dynamic -lpython2.5 -
o bench.so

[EMAIL PROTECTED]:~/sandbox$ mv bench.py pbench.py

[EMAIL PROTECTED]:~/sandbox$ ipython
Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[...]
In [1]: from pbench import bench1 as pbench1

In [2]: from bench import bench1

In [3]: %timeit a = bench1(10)
100 loops, best of 3: 10.2 ms per loop

In [4]: %timeit a = pbench1(10)
10 loops, best of 3: 92.8 ms per loop

--

I guess you'd also see nice improvements from Pyrex or Cython, Blitz
and other tools. Check 

http://wiki.python.org/moin/PythonSpeed/PerformanceTips

for the general ideas and http://scipy.org/PerformancePython for an
insight on available tools that even compares their speeds to Matlab.

And-if-you-run-more-benchmarks-please-do-post-them-ly yrs,
Daniel





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


_
3つの”ホンモノ”プレゼント 賞品第3弾スタート!アルファ スパイダー2.2が当た
る http://clk.atdmt.com/GBL/go/msnjpqjl006010gbl/direct/01/ 

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

Re: How to determine the bool between the strings and ints?

2007-09-07 Thread Marc 'BlackJack' Rintsch
On Fri, 07 Sep 2007 12:26:46 -0700, Zentrader wrote:

> Looks like a "feature" of isinstance() is to consider both True and 1 as
> booleans, but type() distinguishes between the two.

That's not a "feature", it is just OOP.  `bool` is a subclass of `int`
therefore every `bool` instance is also an instance of `int`.  There's
nothing special about it.

In [57]: issubclass(bool, int)
Out[57]: True

In [58]: bool.__base__
Out[58]: 

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Best way to do attribute docstrings?

2007-09-07 Thread Ken Kuhlman

What's the best method for annotating attributes with a docstring?
I'm looking to be able to introspect my class & get the comments back
out.

The technique I'm using is a little hoaky, but works.. basically I
create subclasses of the builtin types that I want to be able to use &
then instantiate them in my attribute assignments.   This gives me an
object that I can tweak the __doc__ attribute on.   An example of what
my code looks like is included below.

I saw that PEP 224 [1] was trying to meet this need, but got rejected
because the proposed syntax wasn't clear enough.

Thanks!
-Ken

[1] http://www.python.org/dev/peps/pep-0224/


attr_doc.py::

# Subclass str so we can modify instance's attributes (like __doc__)
class _(str): pass

# Boolean gave me extra fits that I don't understand, but this
technique works
class MyBool(int):
def __str__(self):
return `self.__int__() > 0`
def __repr__(self):
return self.__str__()

def bool_func(val):
def blah():
   return MyBool(val)
return blah
true = bool_func(True)
false = bool_func(False)


class Animal(object):
four_legs = true()
four_legs.__doc__ = "Animal has four legs"

favorite_food = _('cheese')
favorite_food.__doc__ = "Animal's favorite food"

has_fur = true()
has_fur.__doc__ = "Animal has fur"

print Animal.four_legs.__doc__, '::', Animal.four_legs
print Animal.favorite_food.__doc__, '::', Animal.favorite_food
print Animal.has_fur.__doc__, '::', Animal.has_fur

--
This gives the expected results:

Animal has four legs :: True
Animal's favorite food :: cheese
Animal has fur :: True

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


Re: Python and CUDO

2007-09-07 Thread Robert Kern
Paddy wrote:
> On Sep 6, 10:12 pm, Robert Kern <[EMAIL PROTECTED]> wrote:
>> Veronika Lindstrand Kant wrote:
>>> Hi!
>>> I just wonder if there are any plans for building any support using
>>> NIVIDAS CUDO plattform into python?
>> Not into Python itself, but we are working on interfacing with NVIDIA's CUDA,
>> yes (presuming you actually meant "NVIDIA's CUDA" rather than "NIVIDAS 
>> CUDO").
>>
>> http://code.google.com/p/pystream/
>>
>> --
>> Robert Kern
>>
>> "I have come to believe that the whole world is an enigma, a harmless enigma
>>  that is made terrible by our own mad attempt to interpret it as though it 
>> had
>>  an underlying truth."
>>   -- Umberto Eco
> 
> Maybe you and the CorePy guys at http://www.corepy.org/ could swap
> notes and give us a similar way to work with these accellerators?

We had a productive discussion at the SciPy '07 conference.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Speed of Python

2007-09-07 Thread ajaksu
On Sep 7, 2:37 pm, "wang frank" <[EMAIL PROTECTED]> wrote:
> I am not familiar with python, so I just simply try to reproduce the same
> code in python.
Seems almost correct, but from what I guess of MatLab, George's
suggestions make it a bit more fair.

> If you think that my python script is not efficient, could you tell me how
> to make it more efficient?
In pure Python? No idea (besides using Roberto's and George's
suggestions). If you allow for extensions, Istvan has the answer. If
you allow compiling Python to C++ (using ShedSkin: 
http://shed-skin.blogspot.com/),
here's a small report:

--
[EMAIL PROTECTED]:~/sandbox$ cat bench.py
import math
n = 1
def bench1(n):
for i in range(n):
for j in range(1000):
m=j+1
z=math.log(m)
z1=math.log(m+1)
z2=math.log(m+2)
z3=math.log(m+3)
z4=math.log(m+4)
z5=math.log(m+5)
z6=math.log(m+6)
z7=math.log(m+7)
z8=math.log(m+8)
z9=math.log(m+9)
return z9
a = bench1(10)

[EMAIL PROTECTED]:~/sandbox$ ss -e bench.py
*** SHED SKIN Python-to-C++ Compiler 0.0.22 ***
Copyright 2005-2007 Mark Dufour; License GNU GPL version 2 (See
LICENSE)
(Please send bug reports here: [EMAIL PROTECTED])

[iterative type analysis..]
**
iterations: 2 templates: 44
[generating c++ code..]
[EMAIL PROTECTED]:~/sandbox$ make bench.so
g++  -O3 -s -pipe -fomit-frame-pointer  -I/home/ajaksu/shedskin-0.0.22/
lib -g -fPIC -I/usr/include/python2.5 -D__SS_BIND /home/ajaksu/
shedskin-0.0.22/lib/builtin.cpp /home/ajaksu/shedskin-0.0.22/lib/
math.cpp bench.cpp -lgc  -shared -Xlinker -export-dynamic -lpython2.5 -
o bench.so

[EMAIL PROTECTED]:~/sandbox$ mv bench.py pbench.py

[EMAIL PROTECTED]:~/sandbox$ ipython
Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[...]
In [1]: from pbench import bench1 as pbench1

In [2]: from bench import bench1

In [3]: %timeit a = bench1(10)
100 loops, best of 3: 10.2 ms per loop

In [4]: %timeit a = pbench1(10)
10 loops, best of 3: 92.8 ms per loop

--

I guess you'd also see nice improvements from Pyrex or Cython, Blitz
and other tools. Check http://wiki.python.org/moin/PythonSpeed/PerformanceTips
for the general ideas and http://scipy.org/PerformancePython for an
insight on available tools that even compares their speeds to Matlab.

And-if-you-run-more-benchmarks-please-do-post-them-ly yrs,
Daniel

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

Re: How to determine the bool between the strings and ints?

2007-09-07 Thread Zentrader
On Sep 7, 11:30 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Fri, 07 Sep 2007 18:49:12 +0200, Jorgen Bodde wrote:
> > As for why caring if they are bools or not, I write True and False to
> > the properties, the internal mechanism works like this so I need to
> > make that distinction.
>
> Really?  Can't you just apply the `int()` function?
>
> In [52]: map(int, [1, 0, True, False])
> Out[52]: [1, 0, 1, 0]
>
> Ciao,
> Marc 'BlackJack' Rintsch

Blackjack's solution would take care of the problem, so this is just
for general info.  Looks like a "feature" of isinstance() is to
consider both True and 1 as booleans, but type() distinguishes between
the two.
>>> x=True
... if type(x) == type(1):
...print "int"
... else:
...print "not int"
...
not int

 if type(x) == type(True):
...print "bool"
...
bool

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


Re: creating really big lists

2007-09-07 Thread Dr Mephesto
On 6 Sep., 09:30, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Sep 6, 12:47 am, Dr Mephesto <[EMAIL PROTECTED]> wrote:
>
>
>
> > I need some real speed! a database is waaay to slow for the algorithm
> > im using. and because the sublists are of varying size, i dont think I
> > can use an array...- Hide quoted text -
>
> > - Show quoted text -
>
> How about a defaultdict approach?
>
> from collections import defaultdict
>
> dataArray = defaultdict(lambda : [[],[],[],[],[]])
> dataArray[1001][3].append('x')
> dataArray[42000][2].append('y')
>
> for k in sorted(dataArray.keys()):
> print "%6d : %s" % (k,dataArray[k])
>
> prints:
>   1001 : [[], [], [], ['x'], []]
>  42000 : [[], [], ['y'], [], []]
>
> -- Paul

hey, that defaultdict thing looks pretty cool...

whats the overhead like for using a dictionary in python?

dave

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


Re: Is a Borg rebellion possible? (a metaclass question)

2007-09-07 Thread André
On Sep 7, 4:00 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
> On Fri, 2007-09-07 at 15:54 +, André wrote:
> > Unfortunately, it fails.  Here's what I tried, followed by the
> > traceback
> > class SplinterBorg(object):
> > _shared_states = {}
> > def __new__(cls, *a, **k):
> > group = k.pop("group","BORG")
> > obj = object.__new__(cls, *a, **k)
> > obj.__dict__ = cls._shared_states.setdefault(group,{})
> > return obj
>
> > class MyClass(SplinterBorg):
> >def __init__(self, name):
> >self.name = name
> >[...]
> > Traceback (most recent call last):
> >   File "test.py", line 15, in 
> > b1 = MyClass('b', group="B")
> > TypeError: __init__() got an unexpected keyword argument 'group'
>
> Indeed, if you have an __init__ method that shouldn't see the "group"
> argument, you need a metaclass after all so you can yank the "group"
> argument between __new__ and __init__. The following code seems to work,
> but it's making my brain hurt:
>
> class SplinterBorgMeta(type):
> def __call__(cls, *args, **kwargs):
> inst = cls.__new__(cls, *args, **kwargs)
> kwargs.pop("group",None)
> inst.__init__(*args,**kwargs)
> return inst
>
> class SplinterBorg(object):
> __metaclass__ = SplinterBorgMeta
> _shared_states = {}
> def __new__(cls, *a, **k):
> group = k.pop("group","BORG")
> obj = object.__new__(cls, *a, **k)
> obj.__dict__ = cls._shared_states.setdefault(group,{})
> return obj
>
> class MyClass(SplinterBorg):
> def __init__(self, name):
>self.name = name
>
> The alternatives, as Steve just pointed out, would be not to subclass
> SplinterBorg or to provide an __init__ method that expects a "group"
> argument.
>
> HTH,
>

Thanks for your reply.  I will try to adapt it and see if it works in
my case.

André

> --
> Carsten Haesehttp://informixdb.sourceforge.net


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


Re: unexpected behavior: did i create a pointer?

2007-09-07 Thread Steve Holden
Grant Edwards wrote:
> On 2007-09-07, Peter Otten <[EMAIL PROTECTED]> wrote:
>> Am Fri, 07 Sep 2007 10:40:47 + schrieb Steven D'Aprano:
>>
>>> Python doesn't have any pointers.
>> Thinking of python variables or "names" as pointers should
>> get you a long way when trying to understand python's behaviour.
> 
> But thinking of them as names bound to objects will get you
> further (and get you there faster). ;)
> 
True.

Since it's only a matter of time before someone brings up the "post-It" 
analogy, let me cavil in advance about it. The thing I don't like about 
that particular pedagogic mechanism is that it always "attaches" the 
names to the objects.

To me that blurs the fact that the names live strictly inside 
namespaces, and are destroyed (along with the references they make to 
other objects) when the namespace goes out of scope or otherwise ceases 
to exist (instance destruction being the obvious one).

I only mention this because I too can be a pedantic little bugger when I 
want to be. Have a nice day.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: How to convert None to null value

2007-09-07 Thread Carsten Haese
On Fri, 2007-09-07 at 12:10 -0700, Dennis Lee Bieber wrote:
> On Fri, 07 Sep 2007 09:07:49 -0400, Carsten Haese <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
> 
> > doesn't have a parameter binding mechanism, you should throw it away and
> > replace it with a DB-API complaint module.
> >
>   I hadn't realized the DB-API defined a "complaint" module 

Yeah, I noticed the typo a minute too late. Dyslexics of the world,
untie! ;-)

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Is a Borg rebellion possible? (a metaclass question)

2007-09-07 Thread André
On Sep 7, 3:53 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> André wrote:
> > On Sep 7, 10:27 am, Carsten Haese <[EMAIL PROTECTED]> wrote:
> >> On Fri, 2007-09-07 at 12:31 +, André wrote:
> >>> In my application, I make use of the Borg idiom, invented by Alex
> >>> Martelli.
> >>> class Borg(object):
> >>> '''Borg Idiom, from the Python Cookbook, 2nd Edition, p:273
> >>> Derive a class form this; all instances of that class will share
> >>> the
> >>> same state, provided that they don't override __new__; otherwise,
> >>> remember to use Borg.__new__ within the overriden class.
> >>> '''
> >>> _shared_state = {}
> >>> def __new__(cls, *a, **k):
> >>> obj = object.__new__(cls, *a, **k)
> >>> obj.__dict__ = cls._shared_state
> >>> return obj
> >>> 
> >>> This has worked very well so far, but is starting to impose some
> >>> unwanted constraints on my program design.
> >>> What I would like to do is, to put it figuratively, create a Borg
> >>> rebellion with various splinter groups.  In concrete Python terms, I
> >>> would like to have
> >>> class MyClass(Borg, ...):
> >>>...
> >>> seven_of_nine = MyClass(...)  # part of group "BORG"
> >>> two_of_nine = MyClass(...)
> >>> splinter1 = MyClass(..., group='splinter')
> >>> splinter2 = MyClass(..., group='splinter')
> >>> and have splinter 1 and splinter2 share the same state, but a
> >>> different state than the one shared by members of the BORG collective.
> >>> Any suggestions from the metaclass experts?
> >> You don't need a metaclass. Just turn _shared_state into a dictionary of
> >> shared states, keyed by the group name:
>
> >> class SplinterBorg(object):
> >> _shared_states = {}
> >> def __new__(cls, *a, **k):
> >> group = k.pop("group","BORG")
> >> obj = object.__new__(cls, *a, **k)
> >> obj.__dict__ = cls._shared_states.setdefault(group,{})
> >> return obj
>
> >> HTH,
>
> >> --
> >> Carsten Haesehttp://informixdb.sourceforge.net
>
> > Unfortunately, it fails.  Here's what I tried, followed by the
> > traceback
> > class SplinterBorg(object):
> > _shared_states = {}
> > def __new__(cls, *a, **k):
> > group = k.pop("group","BORG")
> > obj = object.__new__(cls, *a, **k)
> > obj.__dict__ = cls._shared_states.setdefault(group,{})
> > return obj
>
> > class MyClass(SplinterBorg):
> >def __init__(self, name):
> >self.name = name
>
> > a1 = MyClass('a')
> > a2 = MyClass('aa')
> > b1 = MyClass('b', group="B")
>
> > Traceback (most recent call last):
> >   File "test.py", line 15, in 
> > b1 = MyClass('b', group="B")
> > TypeError: __init__() got an unexpected keyword argument 'group'
>
> Because your subclass signature is completely wrong. Why did you feel
> you had to add an __init__() method to your subclass? This has two bvad
> effects:


Because this is what I need to do currently with using the standard
Borg class, and is something I would like to be able to do.  Here's a
simplified version of the current usage I have
=
class Borg(object):
_shared_state = {}
def __new__(cls, *a, **k):
obj = object.__new__(cls, *a, **k)
obj.__dict__ = cls._shared_state
return obj

class BorgConsole(Borg, SingleConsole):
'''Every BorgConsole share a common state'''
def __init__(self, locals={}, filename="Crunchy console"):
SingleConsole.__init__(self, locals, filename=filename)

=
and it is called via something like
a_console = BorgConsole(locals)

where locals is a previously defined dict.   Note that a number of
such instances are created dynamically as the program is used.

What I would like to do is to be able to add a "page_id"   (the Borg
group referred to my previous message), so that I could call

a_console = BorgConsole(locals, page_id)
where page_id would be an optional argument, defaulting to the BORG
group, as mentioned in my original post.

I must admit I did not try with keywords arguments ... and will not be
for a couple of hours while I am at work.


>
> 1. It stops the super-class's __init__() method from being called, and
>
I don't understand why this is so here, and not with the usual Borg
case as I used it...

> 2. It breaks the calling syntax specified in the superclass.
>
> All you really need is to create your SplinterBorgs with appropriate
> group names, you don't neef subclasses at all:
>
> a1 = SplinterBorg(group="one")
> a2 = SplinterBorg(group="two")
>
> and so on.
>
> If you want to create subclasses then they should work like this:
>
> class MyBorg1(SplinterBorg):
>  def __init__(self):
>  SplinterBorg.__init__(self, group='borg1')
>
> and so on, with a different group for each. But this seems over complicated.
>

I do need subclasses (I think) as my classes inherit from more than
the SplinterBorg class...  I'll  see what I can do following some of
your suggestions.

Thanks for the reply,

André

> regards
>   Steve
> --
> 

Re: Python and Cron

2007-09-07 Thread Greg Lindstrom
> "Shawn Milochik" <[EMAIL PROTECTED]>
> Could you send the output of "crontab -l" and the script you're running?
>
> It's probably an environment issue of some kind, but it's hard to say
> what blindly.



# run client pricing at 0215 (p) Monday-Friday
15 2 * * 1-5 cd /m01/edith/src && /usr/bin/python /m01/edith/src/driver.py
--paid-date yesterday --jobname professional >>
/m01/edith/stdout/ecomppo.stdout 2&>1

I've emailed parts of the script in another reply.

Thanks for your time,
--greg
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: unexpected behavior: did i create a pointer?

2007-09-07 Thread Steve Holden
Steven D'Aprano wrote:
> On Fri, 07 Sep 2007 11:46:38 +0200, Wildemar Wildenburger wrote:
> 
>> gu wrote:
>>> hi to all!
>>> after two days debugging my code, i've come to the point that the
>>> problem was caused by an unexpected behaviour of python. or by lack of
>>> some information about the program, of course! i've stripped down the
>>> code to reproduce the problem:
>>>
>>> [snip FAQ]
>> Yes, basically you *created* a pointer. That's all that python has:
>> pointers.
> 
> No, you are confusing the underlying C implementation with Python. Python 
> doesn't have any pointers. CPython is implemented with pointers. PyPy, 
> being written entirely in Python, is implemented with Python objects like 
> lists and dicts. Jython, being implemented in Java, probably isn't 
> implemented with pointers either -- although of course the underlying 
> Java compiler might be. IronPython and Python for .Net, I have no idea 
> how they work. Could be magic for all I know. (Probably necromancy.) 
> 
> Naturally, regardless of whether you are using CPython, IronPython, PyPy 
> or some other variety of Python, the objects available to you include 
> ints, floats, strings, lists, dicts, sets and classes... but not pointers.
> 
> Nor does it include "peek" and "poke" commands for reading and writing 
> into random memory locations. Python is not C, and it is not Basic, nor 
> is it Forth or Lisp or assembler, and you shouldn't hammer the round peg 
> of Python objects into the square hole of C pointers.
> 
This seems to be obscuring the real issue for the sake of hammering an 
error in vocabulary. gu said """Yes, basically you *created* a pointer. 
That's all that python has: pointers.""" and you took issue with that, 
ultimately saying """the objects available to you include ints, floats, 
strings, lists, dicts, sets and classes... but not pointers""".

You are both right, and you are also both wrong.

Python does indeed provide a rich set of strongly typed object classes, 
and so clearly to say "Python only has pointers" is strictly an error. 
However, this overlooks the fact that *all* names in Python, and *all* 
items in container objects (lists, tuples, dicts ...) hold references to 
objects.

I mention this because it *is* significant to the semantics of 
assignment. From the point of view of a C programmer Python might 
actually look quite like a language in which all data objects had to be 
malloc'd, and the only variables were pointers to. Assignment (binding) 
in Python creates copies of references to objects, not copies of the 
objects themselves.

I have deliberately omitted discussion of the automatic dereferencing 
that takes place in Python, thereby allowing us to treat names as though 
they contained objects, but the fact remains that names *don't* contain 
objects, they contain references to objects. If you want to regard a 
reference and a pointer as two different things then I guess that's your 
nit to pick. But I don't think the original assertions quite justified 
your scathing remarks about "peek" and "poke".

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Python and Cron

2007-09-07 Thread Greg Lindstrom
> Can you post the Python script?


Not the whole thing; it's quite long.  But here's the relevant parts.  We're
using the ado database interface into postgres (that's what the
results.EOFis all about)

output_file = file(output_path, 'w')   # output_path =
/my_path/data/work/my_file.txt
while not results.EOF:
row = results.GetRowAssoc(upper=0)
output_file.write(row['data'])
results.MoveNext()
output_file.close()
debug('Total Bytes Written: %d' % total_bytes)

new_path = None
if total_bytes > 0:   new_path = output_path.replace('/work/', '/')
else: new_path = output_path.replace('/work/',
'/empty/')

debug('Original Path [%s]'%output_path)   # new_path =
/my_path/data/my_file.txt
debug(' New Path [%s]'%new_path)  # new_path =
/my_path/data/empty/my_file.txt


The original code looked like this (worked from command line, failed with
cron)

os.rename(output_path, new_path)

But since that didn't work and I could create a new file, I tried this as a
work around

output_file = file(new_path, 'w')
for line in file(output_path):
output_file.write(line)
output_file.close()

The interesting/infuriating thing is that the second method also fails; that
is, the file is not moved to the data directory or the "empty"
directory...it remains in the "work" directory after the cron job
completes.  If I run the same routine from the command like (after su'ing to
the edith user) it runs and moves the file to the appropriate directory.

I am going to see if we can get the email routing set up (we run over 100
cron jobs daily so I'm not sure I want it on too long) to see if it will
tell me anything.


Thanks for your time and effort
--greg



What's the name of the original file, and what are you trying to rename
> it to? I'm wondering if you are deriving the new name from something,
> and that thing is failing from within the cronjob for some reason.
> Perhaps the new name contains a complete path in one of the cases but
> not in the other...
>
> Edith should be getting email (if email routing is set up correctly) if
> the job is failing or producing output. Specifically, perhaps she's
> getting Python tracebacks and not telling you... :)
>
>
>
> --
> pkm ~ http://paulmcnett.com
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Organizing Code - Packages

2007-09-07 Thread Wildemar Wildenburger
Paul Rudin wrote:
> xkenneth <[EMAIL PROTECTED]> writes:
> 
>>> Ah, yes, a couple of things:
>>> - avoid the 'one-class-per-file' syndrom. It's perfectly ok to have tens
>> Yes but i find it hard to edit classes easily when I have more than
>> one class per file.
> 
> Why?
Scroll-Blindness would be a good reason.

It would however be completely rediculous to create a file for every 
10-liner class you have (and I have found that Python classes tend to be 
rather short).

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


Re: Is a Borg rebellion possible? (a metaclass question)

2007-09-07 Thread Carsten Haese
On Fri, 2007-09-07 at 15:54 +, André wrote:
> Unfortunately, it fails.  Here's what I tried, followed by the
> traceback
> class SplinterBorg(object):
> _shared_states = {}
> def __new__(cls, *a, **k):
> group = k.pop("group","BORG")
> obj = object.__new__(cls, *a, **k)
> obj.__dict__ = cls._shared_states.setdefault(group,{})
> return obj
> 
> class MyClass(SplinterBorg):
>def __init__(self, name):
>self.name = name
>[...]
> Traceback (most recent call last):
>   File "test.py", line 15, in 
> b1 = MyClass('b', group="B")
> TypeError: __init__() got an unexpected keyword argument 'group'

Indeed, if you have an __init__ method that shouldn't see the "group"
argument, you need a metaclass after all so you can yank the "group"
argument between __new__ and __init__. The following code seems to work,
but it's making my brain hurt:

class SplinterBorgMeta(type):
def __call__(cls, *args, **kwargs):
inst = cls.__new__(cls, *args, **kwargs)
kwargs.pop("group",None)
inst.__init__(*args,**kwargs)
return inst

class SplinterBorg(object):
__metaclass__ = SplinterBorgMeta
_shared_states = {}
def __new__(cls, *a, **k):
group = k.pop("group","BORG")
obj = object.__new__(cls, *a, **k)
obj.__dict__ = cls._shared_states.setdefault(group,{})
return obj

class MyClass(SplinterBorg):
def __init__(self, name):
   self.name = name

The alternatives, as Steve just pointed out, would be not to subclass
SplinterBorg or to provide an __init__ method that expects a "group"
argument.

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Speed of Python

2007-09-07 Thread Istvan Albert
On Sep 7, 12:42 pm, "wang frank" <[EMAIL PROTECTED]> wrote:

> Is my conclusion correct that Python is slower than matlab?

There are ways to speed up code execution, but to see substantial
improvement you'll need to use numpy and rework the code to operate
on  vectors/matrices rather than building the result one step at the
time. This applies to Octave as well. See the example code at the end
of the message.

With that code computing 1 million logarithms showed the following
tendency

original => 648.972728 msec per pass
optimized => 492.613773 msec per pass
with numpy => 120.578616 msec per pass

The "slowness of python in this example mainly comes from the function
call (math.log) as it seems about 30% of the runtime is spent calling
the function.

import timeit

setup = """
import math
from  numpy import arange, log
size = 1000
"""

code1 = """
#original code
for i in range(size):
for j in range(size):
a = math.log(j+1)
"""

code2 = """
# minor improvements lead to 15% faster speed
from math import log
for i in xrange(size):
for j in xrange(size):
a = log(j+1)
"""

code3 = """
# applying via a universal function makes it 5 times faster
for i in xrange(size):
nums = arange( size )
a = log( nums + 1)
"""

N = 3
codes = [ code1, code2, code3 ]

for stmt in codes:
timer = timeit.Timer(stmt=stmt, setup=setup)
msec  = 1000.0 * timer.timeit(number=N)/N
print "%f msec per pass" % msec

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

Re: Speed of Python

2007-09-07 Thread George Sakkis
On Sep 7, 12:42 pm, "wang frank" <[EMAIL PROTECTED]> wrote:

> Is my conclusion correct that Python is slower than matlab? Are there any
> way to speed it up?

Yes, use Numpy for any non trivial number-crunching task: 
http://numpy.scipy.org/.
Even if you don't, you can speed up the original function by ~25% if
you replace range() with xrange() and bind the log function to a local
variable:

def bench2(n):
from math import log
for i in xrange(n):
for j in xrange(1000):
m=j+1
z=log(m)
z1=log(m+1)
z2=log(m+2)
z3=log(m+3)
z4=log(m+4)
z5=log(m+5)
z6=log(m+6)
z7=log(m+7)
z8=log(m+8)
z9=log(m+9)
return z9


HTH,

George

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

Re: Is a Borg rebellion possible? (a metaclass question)

2007-09-07 Thread Steve Holden
André wrote:
> On Sep 7, 10:27 am, Carsten Haese <[EMAIL PROTECTED]> wrote:
>> On Fri, 2007-09-07 at 12:31 +, André wrote:
>>> In my application, I make use of the Borg idiom, invented by Alex
>>> Martelli.
>>> class Borg(object):
>>> '''Borg Idiom, from the Python Cookbook, 2nd Edition, p:273
>>> Derive a class form this; all instances of that class will share
>>> the
>>> same state, provided that they don't override __new__; otherwise,
>>> remember to use Borg.__new__ within the overriden class.
>>> '''
>>> _shared_state = {}
>>> def __new__(cls, *a, **k):
>>> obj = object.__new__(cls, *a, **k)
>>> obj.__dict__ = cls._shared_state
>>> return obj
>>> 
>>> This has worked very well so far, but is starting to impose some
>>> unwanted constraints on my program design.
>>> What I would like to do is, to put it figuratively, create a Borg
>>> rebellion with various splinter groups.  In concrete Python terms, I
>>> would like to have
>>> class MyClass(Borg, ...):
>>>...
>>> seven_of_nine = MyClass(...)  # part of group "BORG"
>>> two_of_nine = MyClass(...)
>>> splinter1 = MyClass(..., group='splinter')
>>> splinter2 = MyClass(..., group='splinter')
>>> and have splinter 1 and splinter2 share the same state, but a
>>> different state than the one shared by members of the BORG collective.
>>> Any suggestions from the metaclass experts?
>> You don't need a metaclass. Just turn _shared_state into a dictionary of
>> shared states, keyed by the group name:
>>
>> class SplinterBorg(object):
>> _shared_states = {}
>> def __new__(cls, *a, **k):
>> group = k.pop("group","BORG")
>> obj = object.__new__(cls, *a, **k)
>> obj.__dict__ = cls._shared_states.setdefault(group,{})
>> return obj
>>
>> HTH,
>>
>> --
>> Carsten Haesehttp://informixdb.sourceforge.net
> 
> Unfortunately, it fails.  Here's what I tried, followed by the
> traceback
> class SplinterBorg(object):
> _shared_states = {}
> def __new__(cls, *a, **k):
> group = k.pop("group","BORG")
> obj = object.__new__(cls, *a, **k)
> obj.__dict__ = cls._shared_states.setdefault(group,{})
> return obj
> 
> class MyClass(SplinterBorg):
>def __init__(self, name):
>self.name = name
> 
> a1 = MyClass('a')
> a2 = MyClass('aa')
> b1 = MyClass('b', group="B")
> 
> 
> Traceback (most recent call last):
>   File "test.py", line 15, in 
> b1 = MyClass('b', group="B")
> TypeError: __init__() got an unexpected keyword argument 'group'
> 
> 
Because your subclass signature is completely wrong. Why did you feel 
you had to add an __init__() method to your subclass? This has two bvad 
effects:

1. It stops the super-class's __init__() method from being called, and

2. It breaks the calling syntax specified in the superclass.

All you really need is to create your SplinterBorgs with appropriate 
group names, you don't neef subclasses at all:

a1 = SplinterBorg(group="one")
a2 = SplinterBorg(group="two")

and so on.

If you want to create subclasses then they should work like this:

class MyBorg1(SplinterBorg):
 def __init__(self):
 SplinterBorg.__init__(self, group='borg1')

and so on, with a different group for each. But this seems over complicated.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: why should I learn python

2007-09-07 Thread Shawn Milochik
I wholeheartedly second the recommendation of this article:

http://www.linuxjournal.com/article/3882
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Cron

2007-09-07 Thread Paul McNett
Greg Lindstrom wrote:
> This may be more of a Linux question, but I'm hoping some of you may be 
> able to help me.
> 
> I have a python (2.4) routine running on Gentoo Linux.  It creates a 
> file and, after the file is complete, renames the file using the 
> os.rename() command.  When I run the file from the command line 
> everything works great, but when I schedule the job to run from the 
> crontab file, the original file is created and populated, but the rename 
> fails.  I am using full paths for both the original and destination 
> file, and run the command line version after I 'su' to the production 
> account (named 'edith').  I am told by my sysadmin that the cron jobs 
> run as edith as well, so he does not think it is a permission issue (he 
> points out the original file is being created and populated as 
> expected...the rename fails)
> 
> Have any of you dealt with anything like this?  It really has me 
> scratching my head.

Can you post the Python script?

What's the name of the original file, and what are you trying to rename 
it to? I'm wondering if you are deriving the new name from something, 
and that thing is failing from within the cronjob for some reason. 
Perhaps the new name contains a complete path in one of the cases but 
not in the other...

Edith should be getting email (if email routing is set up correctly) if 
the job is failing or producing output. Specifically, perhaps she's 
getting Python tracebacks and not telling you... :)



-- 
pkm ~ http://paulmcnett.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to determine the bool between the strings and ints?

2007-09-07 Thread Marc 'BlackJack' Rintsch
On Fri, 07 Sep 2007 18:49:12 +0200, Jorgen Bodde wrote:

> As for why caring if they are bools or not, I write True and False to
> the properties, the internal mechanism works like this so I need to
> make that distinction.

Really?  Can't you just apply the `int()` function?

In [52]: map(int, [1, 0, True, False])
Out[52]: [1, 0, 1, 0]

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Cron

2007-09-07 Thread Shawn Milochik
Could you send the output of "crontab -l" and the script you're running?

It's probably an environment issue of some kind, but it's hard to say
what blindly.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: passing command line arguments

2007-09-07 Thread Brian McCann
 
Darren,
Thanks
 



From: [EMAIL PROTECTED] on behalf of darren kirby
Sent: Fri 9/7/2007 1:58 PM
To: python-list@python.org
Subject: Re: passing command line arguments



quoth the Brian McCann:
> Hi,
>
> when I run the script show_args2.py
>
> # ./show_args2.py 1 2 3
>
> I get the following error
>
> Traceback (most recent call last):
>   File "./show_args2.py", line 4, in ?
> print 'The arguments of %s are "%s"' %s \
> NameError: name 's' is not defined
>
>
> #
> 
> this is the script
>  #!/usr/bin/python
> import sys, string
> print 'The arguments of %s are "%s"' %s \
> (sys.argv[0], string.join(sys.argv[1:]))

You don't want the 's' on the last format operator. Try:

 print 'The arguments of %s are "%s"' % \
 (sys.argv[0], string.join(sys.argv[1:]))

> any help would be greatly appreciated
>
> -Brian

-d
--
darren kirby :: Part of the problem since 1976 :: http://badcomputer.org
"...the number of UNIX installations has grown to 10, with more expected..."
- Dennis Ritchie and Ken Thompson, June 1972
--
http://mail.python.org/mailman/listinfo/python-list


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

Re: Speed of Python

2007-09-07 Thread Roberto Bonvallet
On Sep 7, 1:37 pm, "wang frank" <[EMAIL PROTECTED]> wrote:
> Hi,
> Here is the matlab code:
> function [z]=bench1(n)
> for i=1:n,
> for j=1:1000,
> z=log(j);
> z1=log(j+1);
> z2=log(j+2);
> z3=log(j+3);
> z4=log(j+4);
> z5=log(j+5);
> z6=log(j+6);
> z7=log(j+7);
> z8=log(j+8);
> z9=log(j+9);
> end
> end
> z = z9;
>
> I am not familiar with python, so I just simply try to reproduce the same
> code in python.
> If you think that my python script is not efficient, could you tell me how
> to make it more efficient?

> > > import math
> > > def bench1(n):
> > > for i in range(n):
> > > for j in range(1000):

The range(1000) call creates a list of 1000 elements each time it is
called.
This is expensive.  You could try something like the following:

def bench1a(n):
r = range(1000)
for i in range(n):
# reuse the list
for j in r:
...

def bench1b(n):
for i in range(n):
# don't use a list at all
j = 0
while j < 1000:
...

I'm no expert on Python optimization either, so I cannot guarantee
that both are
the best way to write this algorithm.

> > > [...]
> > > m=j+1

This step also doesn't occur in the Matlab code.

Hope this helps, although maybe I'm not the right person to talk about
optimization, and I haven't measured my code.

--
Roberto Bonvallet


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

Re: passing command line arguments

2007-09-07 Thread darren kirby
quoth the Brian McCann:
> Hi,
>
> when I run the script show_args2.py
>
> # ./show_args2.py 1 2 3
>
> I get the following error
>
> Traceback (most recent call last):
>   File "./show_args2.py", line 4, in ?
> print 'The arguments of %s are "%s"' %s \
> NameError: name 's' is not defined
>
>
> #
> 
> this is the script
>  #!/usr/bin/python
> import sys, string
> print 'The arguments of %s are "%s"' %s \
> (sys.argv[0], string.join(sys.argv[1:]))

You don't want the 's' on the last format operator. Try:

 print 'The arguments of %s are "%s"' % \
 (sys.argv[0], string.join(sys.argv[1:]))

> any help would be greatly appreciated
>
> -Brian

-d
-- 
darren kirby :: Part of the problem since 1976 :: http://badcomputer.org
"...the number of UNIX installations has grown to 10, with more expected..."
- Dennis Ritchie and Ken Thompson, June 1972
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe - change name of exe created

2007-09-07 Thread Thomas Heller
imageguy schrieb:
[...]
>> > Note that every thing works fine with this and creates an exe program
>> > called
>> > "myprogram.exe"
>>
>> > I would like to setup program to create an output called;
>> > "MyBestProgram.exe"
>>
>> > IS that at all possible ?
>>
>> Yes.  Use a 'dest_base' key in the dictionary, like so:
>>
>> > setup(windows = [{"script":"myprogram.py",
>> >"icon_resources":[(0,"nabbitt.ico")],
>>
>>  "dest_base": "MyBestProgram",> 
>> "other_resources": [(24,1,manifest)]}
>>
>> ...
>>
>> 'dest_base' is the basename of the destination program that py2exe creates.
>>
>> Thomas- Hide quoted text -
>>
>> - Show quoted text -
> 
> Thanks.
> I really appreciate the response.
> Where would I find that in the docs ?  Thought I had searched
> everywhere.


If you have searched everywhere then it isn't in the docs.  You can probably
learn a lot about py2exe when you try out and study the supplied samples; they
are in the Lib\site-packages\py2exe\samples subdirectories.

The next step would be to consult the source code ;-)

The current maintainer of pyexe, Jimmy Retzlaff, seems to have disappeared
from the net as it seems; I hope he is well.  So, the current state of py2exe
itself and the documentation is not so good; OTOH there is a wiki on
www.py2exe.org where anyone can contribute tips tricks and docs.

Thomas

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


Re: passing command line arguments

2007-09-07 Thread Carsten Haese
On Fri, 2007-09-07 at 12:47 -0400, Brian McCann wrote:
>  
> Hi,
>  
> when I run the script show_args2.py
> 
> # ./show_args2.py 1 2 3
> 
> I get the following error
> 
> Traceback (most recent call last):
>   File "./show_args2.py", line 4, in ?
> print 'The arguments of %s are "%s"' %s \
> NameError: name 's' is not defined

Start here: http://catb.org/~esr/faqs/smart-questions.html#before

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Example script -- Group Project Task Scheduler

2007-09-07 Thread nickel_and_dime_2death
Hello, trying to get UpToSpeed with a cross-platform application that
would mimic capabilities like Microsoft Project. Playing around with
code is what works for me. Searching is a mangled process, i.e. I've
banged around terms like: "project", "scheduler", "class scheduler",
"student calendar" ... and on and on. Python descriptions / howtos /
tutorials / documentations have used most of the search terms I can
think of define Python's nuts and bolts. Web research of my quest is
not getting me to any examples I want to see. Really, lang.java: class
scheduler brings up my "ms project" mimic concept for java code. I
want to try Python and pythonic coding.

I want code that would list job tasks in a work-week grid and
ultimately drag a block of text to a new location within that week
scheduler if changes were needed. I anticipate XML for my database,
which is what lead me to Python.

Thanks, if somebody out there can offer pointer(s) to an example(s).

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


Re: getting the current function

2007-09-07 Thread Arnaud Delobelle
On Sep 7, 5:19 pm, Gary Robinson <[EMAIL PROTECTED]> wrote:
> > This all seems a bit too complicated. Are you sure you want to do
> > this? Maybe you need to step back and rethink your problem.
>
> In version 2.1 Python added the ability to add function attributes -- 
> seehttp://www.python.org/dev/peps/pep-0232/for the justifications. A counter 
> probably isn't one of them, I just used that as a quick example of using 
> thisfunc().
>
> I've just never liked the fact that you have to name the function when 
> accessing those attributes from within the function. And I thought there 
> might be other uses for something like thisfunc().
>

You can do this without fiddling with stack frames:

def bindfunction(f):
def bound_f(*args, **kwargs):
return f(bound_f, *args, **kwargs)
bound_f.__name__ = f.__name__
return bound_f

# Use like this:

@bindfunction
def factorial(this_function, n):
if n > 0:
return n * this_function(n - 1)
else:
return 1

# Interactively:

>>> factorial(5)
120
>>> fac = factorial
>>> factorial = "spam"
>>> fac(8)
40320
>>>

--
Arnaud


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


Re: Speed of Python

2007-09-07 Thread wang frank
Hi, 
Here is the matlab code:

function [z]=bench1(n)
for i=1:n,
   for j=1:1000,
   z=log(j);
   z1=log(j+1);
   z2=log(j+2);
   z3=log(j+3);
   z4=log(j+4);
   z5=log(j+5);
   z6=log(j+6);
   z7=log(j+7);
   z8=log(j+8);
   z9=log(j+9);
   end
end
z = z9;

I am not familiar with python, so I just simply try to reproduce the same 
code in python.
If you think that my python script is not efficient, could you tell me how 
to make it more efficient?


Thanks

Frank


From: Roberto Bonvallet <[EMAIL PROTECTED]>
To: python-list@python.org
Subject: Re: Speed of Python
Date: Fri, 07 Sep 2007 17:19:02 -

On Sep 7, 12:42 pm, "wang frank" <[EMAIL PROTECTED]> wrote:
> Here is the bench1.py:
> import math
> def bench1(n):
> for i in range(n):
> for j in range(1000):
> m=j+1
> z=math.log(m)
> z1=math.log(m+1)
> z2=math.log(m+2)
> z3=math.log(m+3)
> z4=math.log(m+4)
> z5=math.log(m+5)
> z6=math.log(m+6)
> z7=math.log(m+7)
> z8=math.log(m+8)
> z9=math.log(m+9)
> return z9
>
> Is my conclusion correct that Python is slower than matlab?

Show us your Matlab code in order to see if both are equivalent.
Your Python code creates n lists of 1000 elements, so you're not
actually
measuring only the numeric computations.

Cheers,
--
Roberto Bonvallet





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


_
メッセンジャー用アイコンに大人気オンラインゲームの萌えなキャラが登場! 
http://messenger.live.jp/ 

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

Re: startswith( prefix[, start[, end]]) Query

2007-09-07 Thread Steve Holden
Bruno Desthuilliers wrote:
> Steve Holden a écrit :
[...]
>>
>> Probably not really necessary, though, and they do say that premature 
>> optimization is the root of all evil ...
> 
> I wouldn't call this one "premature" optimization, since it doesn't 
> change the algorithm, doesn't introduce (much) complication, and is 
> proven to really save on lookup time.
> 
> Now I do agree that unless you have quite a lot of prefixes to test, it 
> might not be that necessary in this particular case...

The defense rests.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Why 'class spam(object)' instead of class spam(Object)' ?

2007-09-07 Thread Steve Holden
Carl Banks wrote:
> On Fri, 07 Sep 2007 01:30:00 -0500, Sergio Correia wrote:
>> Hi, I'm kinda new to Python (that means, I'm a total noob here), but
>> have one doubt which is more about consistency that anything else.
>>
>> Why if PEP 8 says that "Almost without exception, class names use the
>> CapWords convention", does the most basic class, object, is lowercase?
> 
> It said "almost".  :)
> 
Indeed it did, and never forget that most of PEP 8 was derived from an 
essay by Guido whose original title was "A Foolish Consistency is the 
Hobgoblin of Little Minds" ...
> 
>> I found a thread about this:
>> http://mail.python.org/pipermail/python-list/2007-April/437365.html
>> where its stated that -object- is actually a type, not a class; but the
>> idea still doesn't convince me.
> 
You don't have to be convinced. You just have to do what the PEP says 
yourself and ignore the people who *haven't* done what it says 
(particularly if they are core Python developers).

> There's a false dichotomy there: it's not an either-or situation.  Almost 
> everyone would agree that new-style classes, defined by the Python class 
> statement, are both classes and types.  Some might squabble over whether 
> object is class, but it has nothing to do with why object is spelled in 
> lower-case.
> 
> The reason why "object" is lower case is because built-in types are 
> spelled in lower-case.  Why are built-in types lower case?  Because many 
> built-in types were originially functions.  For example, "int" and "str" 
> were once functions.  When these symbols became the names of their 
> respective types, they kept the lower-case spelling, and it became 
> convention for built-in types to be spelled lower-case.
> 
In other words: "Get over it" ;-)

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: library to launch program in linux

2007-09-07 Thread Neil Cerutti
On 2007-09-07, Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
> In message <[EMAIL PROTECTED]>, Laszlo Nagy
> wrote:
>
>> Grant Edwards wrote:
>>
>>> On 2007-09-06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>>>   
 I'm a new user. What library should I use so that I can launch
 program in linux using python?
 
>>>
>>> subprocess
>>>   
>> Hmm, there are some others...
>
> subprocess subsumes them all.

And someday soon, subprocess will RULE THE WORLD! BWA-HAHAHAHAH!

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


Re: interesting puzzle......try this you will be rewarded...

2007-09-07 Thread Neil Cerutti
On 2007-09-07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> En Thu, 06 Sep 2007 22:57:21 -0300, Basilisk96 <[EMAIL PROTECTED]>  
> escribi?:
>
>> I got to 14 :)
>>
>> It's rather silly.
>>
>> I remember seeing a more elaborate puzzle that involved coding,
>> cryptography knowledge, etc. to get through it. But what was the link,
>> I forget now...
>
> Me too, and I can't find that link either. #15 is a bit
> difficult for people outside US, and spelling on #21 is
> questionable, but I liked this woody thing :)

Y'all may be thinking of The Euler Project, which provides math
puzzles for programmers.

http://projecteuler.net/

-- 
Neil Cerutti
I pulled away from the side of the road, glanced at my mother-in-law and
headed over the embankment. --Insurance Claim Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Python and Cron

2007-09-07 Thread Greg Lindstrom
This may be more of a Linux question, but I'm hoping some of you may be able
to help me.

I have a python (2.4) routine running on Gentoo Linux.  It creates a file
and, after the file is complete, renames the file using the os.rename()
command.  When I run the file from the command line everything works great,
but when I schedule the job to run from the crontab file, the original file
is created and populated, but the rename fails.  I am using full paths for
both the original and destination file, and run the command line version
after I 'su' to the production account (named 'edith').  I am told by my
sysadmin that the cron jobs run as edith as well, so he does not think it is
a permission issue (he points out the original file is being created and
populated as expected...the rename fails)

Have any of you dealt with anything like this?  It really has me scratching
my head.

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

Re: Speed of Python

2007-09-07 Thread Roberto Bonvallet
On Sep 7, 12:42 pm, "wang frank" <[EMAIL PROTECTED]> wrote:
> Here is the bench1.py:
> import math
> def bench1(n):
> for i in range(n):
> for j in range(1000):
> m=j+1
> z=math.log(m)
> z1=math.log(m+1)
> z2=math.log(m+2)
> z3=math.log(m+3)
> z4=math.log(m+4)
> z5=math.log(m+5)
> z6=math.log(m+6)
> z7=math.log(m+7)
> z8=math.log(m+8)
> z9=math.log(m+9)
> return z9
>
> Is my conclusion correct that Python is slower than matlab?

Show us your Matlab code in order to see if both are equivalent.
Your Python code creates n lists of 1000 elements, so you're not
actually
measuring only the numeric computations.

Cheers,
--
Roberto Bonvallet

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

Re: Speed of Python

2007-09-07 Thread S bastien Boisg rault

On Sep 7, 6:42 pm, "wang frank" <[EMAIL PROTECTED]> wrote:

Matlab (aka MATrix LABoratory) has been designed with numeric
computations in mind (every object being natively a n-dim
array). If you wish to develop that kind of applications in
Python, consider using the numerical array structure provided
by Numpy. Numpy being mostly written in C, that should speed
up your application ... In this context, additional 3rd party
libs such as Scipy, Matplotlib, PIL, etc. will also be useful.

Cheers,

SB

> Hi,
>
> While comparing the speed of octave and matlab, I decided to do a similar
> test for python and matlab. The result shows that python is slower than
> matlab by a factor of 5. It is not bad since octave is about 30 time slower
> than matlab.
>
> Here is the result in matlab:
> Elapsed time is 0.015389 seconds.
>
> and in Python:>>> t=timeit.Timer("bench1.bench1(10)","import bench1")
> >>> t.repeat(1,1)
>
> [0.071012377266015392]
>
> Here is the bench1.py:
> import math
> def bench1(n):
> for i in range(n):
> for j in range(1000):
> m=j+1
> z=math.log(m)
> z1=math.log(m+1)
> z2=math.log(m+2)
> z3=math.log(m+3)
> z4=math.log(m+4)
> z5=math.log(m+5)
> z6=math.log(m+6)
> z7=math.log(m+7)
> z8=math.log(m+8)
> z9=math.log(m+9)
> return z9
>
> Is my conclusion correct that Python is slower than matlab? Are there any
> way to speed it up? It seems Python automatically created bench1.pyc. Does
> Python automatically execute the bench1.pyc to speed it up?
>
> Thanks
>
> Frank
>
> _
> 「地図マガ」特集 残暑を吹きとばせ!ご当地アイスクリームマップが登場http://chizumaga.jp/


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

Re: concise code (beginner)

2007-09-07 Thread Rhamphoryncus
On Sep 6, 1:56 pm, Karthik Gurusamy <[EMAIL PROTECTED]> wrote:
> That said, it may be a good future language enhancement to define a
> reasonable consistent behavior for an iterator over a changing
> collection. This occurs quite common when we walk a collection and
> usually delete the current item.
>
> For a sequence, what the expected behavior is quite obvious (just
> remove this element and go over to the next). For other collections
> like dictionary/set, again if the operation is delete, the expected
> behavior is obvious. If we are doing insertion, for sequence a well-
> defined behavior can be formulated (based on insert before or after
> current position -- if after we will see it in the walk, if before we
> won't see it) . For dict/set I see this isn't simple (as based on hash
> key we may insert ahead or later of the current 'cursor'/position.

Removing from a list while you iterate will had quadratic performance
though.  O(n) to find the element you wish to remove and move over
everything after it, multiplied by your original O(n) of iterating,
gives O(n**2).  That, combined with the fact that adding enough
accounting to invalidate or update your iterator would be a cost on
all the correct users too, is why it's not done.

The best approach in almost all cases in python is to create a new
container as you iterate over the old one.  After you finish, you
replace the old one with the new one.  This lets you keep an overall
O(n) performance, as well as avoiding the tricky semantics.

--
Adam Olsen, aka Rhamphoryncus

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


Re: How to determine the bool between the strings and ints?

2007-09-07 Thread Jorgen Bodde
Awesome! Thanks you!

As for why caring if they are bools or not, I write True and False to
the properties, the internal mechanism works like this so I need to
make that distinction.

Thanks again guys,
- Jorgen

ps. Sorry TheFlyingDutch for mailing you personally, I keep forgetting
this mailinglist does not default back to the user list when replying
;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


passing command line arguments

2007-09-07 Thread Brian McCann
 
Hi,
 
when I run the script show_args2.py

# ./show_args2.py 1 2 3

I get the following error

Traceback (most recent call last):
  File "./show_args2.py", line 4, in ?
print 'The arguments of %s are "%s"' %s \
NameError: name 's' is not defined


#
 
this is the script
 #!/usr/bin/python
import sys, string
print 'The arguments of %s are "%s"' %s \
(sys.argv[0], string.join(sys.argv[1:]))

 

any help would be greatly appreciated

-Brian


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

Re: Organizing Code - Packages

2007-09-07 Thread Paul Rudin
xkenneth <[EMAIL PROTECTED]> writes:

>> Ah, yes, a couple of things:
>> - avoid the 'one-class-per-file' syndrom. It's perfectly ok to have tens
>
> Yes but i find it hard to edit classes easily when I have more than
> one class per file.

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


Speed of Python

2007-09-07 Thread wang frank
Hi, 

While comparing the speed of octave and matlab, I decided to do a similar 
test for python and matlab. The result shows that python is slower than 
matlab by a factor of 5. It is not bad since octave is about 30 time slower 
than matlab.


Here is the result in matlab:
Elapsed time is 0.015389 seconds.

and in Python:

t=timeit.Timer("bench1.bench1(10)","import bench1")
t.repeat(1,1)

[0.071012377266015392]

Here is the bench1.py:
import math
def bench1(n):
for i in range(n):
for j in range(1000):
m=j+1
z=math.log(m)
z1=math.log(m+1)
z2=math.log(m+2)
z3=math.log(m+3)
z4=math.log(m+4)
z5=math.log(m+5)
z6=math.log(m+6)
z7=math.log(m+7)
z8=math.log(m+8)
z9=math.log(m+9)
return z9   

Is my conclusion correct that Python is slower than matlab? Are there any 
way to speed it up? It seems Python automatically created bench1.pyc. Does 
Python automatically execute the bench1.pyc to speed it up?



Thanks

Frank

_
「地図マガ」特集 残暑を吹きとばせ!ご当地アイスクリームマップが登場 
http://chizumaga.jp/ 

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

Re: Organizing Code - Packages

2007-09-07 Thread xkenneth

> Ah, yes, a couple of things:
> - avoid the 'one-class-per-file' syndrom. It's perfectly ok to have tens

Yes but i find it hard to edit classes easily when I have more than
one class per file.

Regards,
Ken

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


Re: How to determine the bool between the strings and ints?

2007-09-07 Thread TheFlyingDutchman
On Sep 7, 8:40 am, "Jorgen Bodde" <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> I have a dictionary with settings. The settinfgs can be strings, ints
> or bools. I would like to write this list dynamically to disk in a big
> for loop, unfortunately the bools need to be written as 0 or 1 to the
> config with WriteInt, the integers also with WriteInt and the strings
> with a simple Write.
>
> The list is something like;
>
> options[A] = True
> options[B] = 1
> options[C] = "Hello"
>
> I wanted to use isinstance to determine if it is a bool or an int or a
> string. However I am confused trying it out in the interactive editor;
>
> >>> a = False
> >>> if isinstance(a, bool):
>
> ... print "OK"
> ...
> OK>>> if isinstance(a, int):
>
> ... print "OK"
> ...
> OK
>
>
>
> I don't get it. is the bool derived from 'int' in some way? What is
> the best way to check if the config I want to write is an int or a
> bool ?
>
> Regards,
> - Jorgen

This came up in a discussion within the last two weeks but I cannot
find it in a search of google.

It appear that you can get the exact class (as opposed to "is this
class or a derivative" that isinstance() seems to provide)
 with the  __class__ attribute:


>>> a = True
>>> print a.__class__ == bool
True
>>> print a.__class__ == int
False
>>> b = 1
>>> print b.__class__ == int
True
>>> print b.__class__  == bool
False




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


Re: py2exe - change name of exe created

2007-09-07 Thread imageguy
On Sep 7, 11:22 am, Thomas Heller <[EMAIL PROTECTED]> wrote:
> imageguy schrieb:
>
>
>
>
>
> > Sorry for the double post, sent it to quickly.
>
> > I have a setup script like this;
>
> > setup(windows = [{"script":"myprogram.py",
> >"icon_resources":[(0,"nabbitt.ico")],
> > "other_resources": [(24,1,manifest)]}
> > ],
> > name = "My Program ver 0.1",
> > data_files = [("",rootdata)],
> > zipfile = None,
> > options = {"py2exe": {
> >"compressed" : 1,
> >"dll_excludes":
> > ["w9xpopen.exe"],
> > "bundle_files": 3
> > }
> > },
> > )
>
> > Note that every thing works fine with this and creates an exe program
> > called
> > "myprogram.exe"
>
> > I would like to setup program to create an output called;
> > "MyBestProgram.exe"
>
> > IS that at all possible ?
>
> Yes.  Use a 'dest_base' key in the dictionary, like so:
>
> > setup(windows = [{"script":"myprogram.py",
> >"icon_resources":[(0,"nabbitt.ico")],
>
>  "dest_base": "MyBestProgram",> 
> "other_resources": [(24,1,manifest)]}
>
> ...
>
> 'dest_base' is the basename of the destination program that py2exe creates.
>
> Thomas- Hide quoted text -
>
> - Show quoted text -

Thanks.
I really appreciate the response.
Where would I find that in the docs ?  Thought I had searched
everywhere.

G.

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


re: getting the current function

2007-09-07 Thread Gary Robinson
> This all seems a bit too complicated. Are you sure you want to do
> this? Maybe you need to step back and rethink your problem.

In version 2.1 Python added the ability to add function attributes -- see 
http://www.python.org/dev/peps/pep-0232/ for the justifications. A counter 
probably isn't one of them, I just used that as a quick example of using 
thisfunc(). 

I've just never liked the fact that you have to name the function when 
accessing those attributes from within the function. And I thought there might 
be other uses for something like thisfunc().

-- 

Gary Robinson
CTO
Emergent Music, LLC
[EMAIL PROTECTED]
207-942-3463
Company: http://www.goombah.com
Blog:http://www.garyrobinson.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why should I learn python

2007-09-07 Thread JeffHua
 
In a message dated 2007-9-7 7:50:32, [EMAIL PROTECTED] writes:

Tom  Brown wrote:

> On Thursday 06 September 2007 15:44, Torsten Bronger  wrote:
>> Hallöchen!
>>
>> Tom Brown  writes:
>> > [...] Python has been by far the easiest to develop  in.  Some
>> > people might say it is not "real programming"  because it is so
>> > easy.
>>
>> I can't  believe this.  Have you really heard such a statement?
> 
>  Yes. I was told this by a C programmer. Something about doing it all
>  yourself and not using provided packages. I countered with something  about
> reinventing the wheel. :)

Point this so-called "C  Programmer" toward Henry Spencer's "Ten Commandments
of C  Programming".  Note in particular rule 7:

7. Thou shalt study thy libraries and strive not to reinvent  them
without cause, that thy code  may be short and readable and thy
days pleasant and productive.

You can find the whole list  here:

http://www.everything2.com/index.pl?node_id=783755

-- 
_http://mail.python.org/mailman/listinfo/python-list_ 
(http://mail.python.org/mailman/listinfo/python-list) 


 
 
 
[EMAIL PROTECTED] (mailto:[EMAIL PROTECTED]) ? This seems  like Bill 
Gates' email,does he also like Python? :-)



** Get a sneak peek of the all-new AOL at 
http://discover.aol.com/memed/aolcom30tour
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Is a Borg rebellion possible? (a metaclass question)

2007-09-07 Thread André
On Sep 7, 10:27 am, Carsten Haese <[EMAIL PROTECTED]> wrote:
> On Fri, 2007-09-07 at 12:31 +, André wrote:
> > In my application, I make use of the Borg idiom, invented by Alex
> > Martelli.
>
> > class Borg(object):
> > '''Borg Idiom, from the Python Cookbook, 2nd Edition, p:273
>
> > Derive a class form this; all instances of that class will share
> > the
> > same state, provided that they don't override __new__; otherwise,
> > remember to use Borg.__new__ within the overriden class.
> > '''
> > _shared_state = {}
> > def __new__(cls, *a, **k):
> > obj = object.__new__(cls, *a, **k)
> > obj.__dict__ = cls._shared_state
> > return obj
>
> > 
> > This has worked very well so far, but is starting to impose some
> > unwanted constraints on my program design.
>
> > What I would like to do is, to put it figuratively, create a Borg
> > rebellion with various splinter groups.  In concrete Python terms, I
> > would like to have
>
> > class MyClass(Borg, ...):
> >...
>
> > seven_of_nine = MyClass(...)  # part of group "BORG"
> > two_of_nine = MyClass(...)
>
> > splinter1 = MyClass(..., group='splinter')
> > splinter2 = MyClass(..., group='splinter')
>
> > and have splinter 1 and splinter2 share the same state, but a
> > different state than the one shared by members of the BORG collective.
>
> > Any suggestions from the metaclass experts?
>
> You don't need a metaclass. Just turn _shared_state into a dictionary of
> shared states, keyed by the group name:
>
> class SplinterBorg(object):
> _shared_states = {}
> def __new__(cls, *a, **k):
> group = k.pop("group","BORG")
> obj = object.__new__(cls, *a, **k)
> obj.__dict__ = cls._shared_states.setdefault(group,{})
> return obj
>
> HTH,
>
> --
> Carsten Haesehttp://informixdb.sourceforge.net

Unfortunately, it fails.  Here's what I tried, followed by the
traceback
class SplinterBorg(object):
_shared_states = {}
def __new__(cls, *a, **k):
group = k.pop("group","BORG")
obj = object.__new__(cls, *a, **k)
obj.__dict__ = cls._shared_states.setdefault(group,{})
return obj

class MyClass(SplinterBorg):
   def __init__(self, name):
   self.name = name

a1 = MyClass('a')
a2 = MyClass('aa')
b1 = MyClass('b', group="B")


Traceback (most recent call last):
  File "test.py", line 15, in 
b1 = MyClass('b', group="B")
TypeError: __init__() got an unexpected keyword argument 'group'


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


Re: How to determine the bool between the strings and ints?

2007-09-07 Thread Bruno Desthuilliers
Jorgen Bodde a écrit :
> Hi All,
> 
> I have a dictionary with settings. The settinfgs can be strings, ints
> or bools. I would like to write this list dynamically to disk in a big
> for loop, unfortunately the bools need to be written as 0 or 1 to the
> config with WriteInt, the integers also with WriteInt and the strings
> with a simple Write.
> 
> The list is something like;
> 
> options[A] = True
> options[B] = 1
> options[C] = "Hello"
> 
> I wanted to use isinstance to determine if it is a bool or an int or a
> string. However I am confused trying it out in the interactive editor;
> 
 a = False
 if isinstance(a, bool):
> ...   print "OK"
> ...   
> OK
 if isinstance(a, int):
> ...   print "OK"
> ...   
> OK
> 
> I don't get it. is the bool derived from 'int' in some way?

Obviously : yes !-)

> What is
> the best way to check if the config I want to write is an int or a
> bool ?

 >>> isinstance(0, bool)
False
 >>> isinstance(1, bool)
False
 >>>

But anyway, I don't get the point, since "the bools need to be written 
as 0 or 1 to the config with WriteInt, the integers also with WriteInt". 
So you just don't care if it's a bool or not ? Or did I miss something ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating a unique identifier

2007-09-07 Thread Paul Rubin
Paul Rubin  writes:
> def unique_id():
>return os.urandom(10).encode('hex')

Sorry, make that 32 or 40 instead of 10, if the number of id's is large,
to make birthday collisions unlikely.

If you don't want the id's to be that large, you can implement a
Feistel cipher using md5 or sha as the round function pretty
straightforwardly, then just feed successive integers through it.
That also guarantees uniqueness, at least within one run of the
program.  I have some sample code around for that, let me know if you
need it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating a unique identifier

2007-09-07 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> def unique_id():
> n = 1234567890
> while True:
> yield n
> n += 1

unique_id = itertools.count(1234567890)

> which is easy enough, but I thought I'd check if there was an existing 
> solution in the standard library that I missed. Also, for other 
> applications, I might want them to be rather less predictable.

def unique_id():
   return os.urandom(10).encode('hex')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Organizing Code - Packages

2007-09-07 Thread Bruno Desthuilliers
xkenneth a écrit :
> All,
> 
> I apologize if this is a commonly asked question, but I didn't
> find anything that answered my question while searching.
> 
> So what I have right now is a few packages that contain some commonly
> used functions and another package that contains all of my custom
> error classes. I want these error classes available to me in all of
> the other packages in my library. Currently to achieve this at the top
> of every module file I have the line "from My.Library.Errors import
> *", my problem with this is that it manages to import the Errors into
> every scope that they are used. 

Ain't that what you want ??? Having "these error classes available to me 
in all of the other packages in my library" ?

If you're worried about perfs or whatever, don't worry, a module is only 
imported once - next imports will only bind the names in the importing 
namespace.

> I'm still pretty new to Python, and my
> approachs are probably very rooted in C/C++ (I've had the hardest time
> getting over not being able to overload functions), but am I doing
> this correctly?

Yes, that's the right thing to do.

>Also, are there any good tutorials/examples out there of how to
> organize your python code into packges?

Most of the Python-specific aspects should be covered by the tutorial 
(the one in the doc). Else, it's as usual, trying to have high cohesion 
and low coupling.

Ah, yes, a couple of things:
- avoid the 'one-class-per-file' syndrom. It's perfectly ok to have tens 
of classes in a same module
- plain functions are ok too - no need to stick everything in classes.

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


How to determine the bool between the strings and ints?

2007-09-07 Thread Jorgen Bodde
Hi All,

I have a dictionary with settings. The settinfgs can be strings, ints
or bools. I would like to write this list dynamically to disk in a big
for loop, unfortunately the bools need to be written as 0 or 1 to the
config with WriteInt, the integers also with WriteInt and the strings
with a simple Write.

The list is something like;

options[A] = True
options[B] = 1
options[C] = "Hello"

I wanted to use isinstance to determine if it is a bool or an int or a
string. However I am confused trying it out in the interactive editor;

>>> a = False
>>> if isinstance(a, bool):
... print "OK"
... 
OK
>>> if isinstance(a, int):
... print "OK"
... 
OK
>>>

I don't get it. is the bool derived from 'int' in some way? What is
the best way to check if the config I want to write is an int or a
bool ?

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


  1   2   >