python optimization

Thomas Heller theller at python.net
Thu Sep 15 10:01:47 EDT 2005


Reinhold Birkenfeld <reinhold-birkenfeld-nospam at wolke7.net> writes:

> David Wilson wrote:
>> For the most part, CPython performs few optimisations by itself. You
>> may be interested in psyco, which performs several heavy optimisations
>> on running Python code.
>> 
>> http://psyco.sf.net/
>> 
>> Defining a function inside a loop in CPython will cause a new function
>> object to be created each and every time the loop runs. No such
>> automatic optimisation is performed there. For the most part, this lack
>> of opimisation not only simplifies the CPython implementation, but also
>> causes code to act much more closely to how it was defined, which is
>> good for new and advanced users alike.
>
> More importantly, since Python supports lexical scopes, a function defined
> in a loop could be different each time it is defined, e.g.
>
> def getadders(to):
>     for i in range(to):
>         def adder(amount):
>             return i + amount
>         yield adder

Hehe.  Dangerous code.

>>> def getadders(to):
...     for i in range(to):
...         def adder(amount):
...             return i + amount
...         yield adder
...
>>>
>>> for f in getadders(3):
...     print f(42)
...
42
43
44
>>>

Seems to work.  But observe this:

>>> def getadders(to):
...     for i in range(to):
...         def adder(amount):
...             return i + amount
...         yield adder
...
>>>
>>> funcs = [x for x in getadders(3)]
>>> for f in funcs:
...     print f(42)
...
44
44
44
>>>

Thomas



More information about the Python-list mailing list