Strange behavior when printing a returned closure function

Jean-Paul Calderone exarkun at divmod.com
Sun Mar 25 07:04:32 EDT 2007



On 25 Mar 2007 03:59:52 -0700, dartsch at dicad.de wrote:
>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 ...?

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



More information about the Python-list mailing list