[Python-Dev] Garbage collecting closures

Jeremy Hylton jeremy@alum.mit.edu
11 Apr 2003 23:38:14 -0400


On Fri, 2003-04-11 at 19:59, Paul Prescod wrote:
> Does this bug look familiar to anyone?

No bug here.

> import gc
> 
> def bar(a):
>      def foo():
>          return None
>          x = a
>          foo()
> 
> class C:pass
> a = C()
> 
> for i in range(20):
>      print len(gc.get_referrers(a))
>      x = bar(a)
> 
> On my Python, it just counts up. "a" gets more and more referrers and 
> they are "cell" objects. If it is unknown, I'll submit a bug report 
> unless someone fixes it before I get to it. ;)

Nested recursive functions create circular references, which are only
collected when the garbage collector runs.  Add a gc.collect() call to
the end of your loop and the number of referrers stays at 1.

Jeremy