Strange behavior when printing a returned closure function

dartsch at dicad.de dartsch at dicad.de
Sun Mar 25 06:59:52 EDT 2007


Hello,

when I execute the following code (python 2.5)

def f(x):
    def g():
        return x
    return g

print f(1)
print f(2)

I get an output like

<function g at 0x00AFC1F0>
<function g at 0x00AFC1F0>

So according to print I get the same function object returned at both
calls.
That's surprising, I would expect to get two distinct function objects
because their func_closure attribute has to be different. And indeed,
if I do

print f(1) is f(2)

instead, it prints False. Even more confusing, if I do

g1 = f(1)
g2 = f(2)
print g1
print g2

I get something like

<function g at 0x00AFC1B0>
<function g at 0x00AFC1F0>

ie. two distinct function objects are printed.

What's happening here?
Some clever optimization reusing function objects in special cases or
what ...?

Thomas




More information about the Python-list mailing list