[Python-Dev] Garbage collecting closures
Phillip J. Eby
pje@telecommunity.com
Mon, 14 Apr 2003 11:52:16 -0400
>Then, that gets clarified to
>"unless they have reference cycles, in which case they may get destroyed
>arbitrarily later" and now "or they are used in a function containing
>another function, which will cause a circular reference involving all
>local variables."
Actually, the issue is that *recursive* nested functions create a circular
reference. Note that the body of function 'foo' contains a reference to
'foo'. *That* is the circular reference.
If I understand correctly, it should also be breakable by deleting 'foo'
from the outer function when you're done with it. E.g.:
def bar(a):
def foo():
return None
x = a
foo()
del foo # clears the cell and breaks the cycle
Strangely, I could have sworn that there was documentation that came out
when nested scopes were introduced that discussed this issue. But I just
looked at PEP 227 and the related "What's New" document, and neither
explicitly mentions that defining recursive nested functions creates a
circular reference. I think I just "knew" that it would do so, from what
*is* said in those documents and what little I knew about how the cells
mechanism was supposed to work.
Since both PEP 227 and the What's New document mention recursive nested
functions as a motivating example for nested scopes, perhaps they should
mention the circular reference consequence of doing so.