Strange behavior when printing a returned closure function

D

dartsch

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
 
D

dartsch

They're _not_ the same function object, just like the `is' test told you.
They just happen to have been allocated at the same memory address.

Jean-Paul

ah yes, I see, thanks
 
S

Steven D'Aprano

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.

Not the same function object. The first object is printed, then deleted
by the garbage collector because it goes out of scope. Then the second one
is created and just happens to end up in the same memory location. That's
an accident of the garbage collector implementation.

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
[snip]

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

ie. two distinct function objects are printed.

This time the first function still exists when the second is created, so
the second naturally can't be in the same memory location.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,996
Messages
2,570,238
Members
46,826
Latest member
robinsontor

Latest Threads

Top