Strange behavior when printing a returned closure function

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sun Mar 25 07:50:36 EDT 2007


On Sun, 25 Mar 2007 03:59:52 -0700, dartsch wrote:


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



-- 
Steven.




More information about the Python-list mailing list