[Python-Dev] Garbage collecting closures

Samuele Pedroni pedronis@bluewin.ch
Mon, 14 Apr 2003 22:37:34 +0200


At 12:32 14.04.03 -0700, Paul Prescod wrote:

>Buggy:
>
>def b():
>     def a():
>         if something:
>             a()
>     a()
>     # ten thousand lines of code
>     junk = com_object.do_something()

a should refer and close over junk otherwise nothing bad happens.

 >>> class X:
...  def __del__(self):
...   print "dying"
...
 >>> def b(x):
...  def a(n):
...    if n: a(n-1)
...  a(1)
...  junk = x
...
 >>> b(X())
dying

vs.

 >>> def b(x):
...   def a(n):
...    if n: a(n-1)
...    junk
...   junk = x
...
 >>> b(X())
 >>> gc.collect()
dying
10

regards