Finding closures through introspection

Ian Kelly ian.g.kelly at gmail.com
Tue Jun 15 00:39:16 EDT 2010


On Mon, Jun 14, 2010 at 9:46 PM, John Nagle <nagle at animats.com> wrote:
> No indication there that "fbar" is a closure inside "foo".  There
> are "__closure__" and "__func_closure__" entries in there, but
> they are both None.  A non-closure function has the same entries.
>
> So how can I detect a closure?

Maybe because it has no non-local references, so it's not really a closure?

>>> def foo(x):
...   global fbar
...   def bar(y):
...     pass
...   fbar = bar
...
>>> foo(0)
>>> fbar.func_closure
>>>
>>> def foo(x):
...   global fbar
...   def bar(y):
...     x
...   fbar = bar
...
>>> foo(0)
>>> fbar.func_closure
(<cell at 0x7ffb7dbd8210: int object at 0xa9f2b0>,)

Cheers,
Ian



More information about the Python-list mailing list