python optimization

Reinhold Birkenfeld reinhold-birkenfeld-nospam at
Thu Sep 15 15:32:15 CEST 2005

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.
> 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


More information about the Python-list mailing list