[Python-Dev] Garbage collecting closures

Phillip J. Eby pje@telecommunity.com
Mon, 14 Apr 2003 12:08:38 -0400

At 11:58 AM 4/14/03 -0400, Jeremy Hylton wrote:
>On Mon, 2003-04-14 at 11:52, Phillip J. Eby wrote:
> > 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
> >
>You haven't tried this, have you? ;-)

Well, I did say, "If I understand correctly".  :)

What's funny is, I could've sworn I've used 'del' under similar 
circumstances before. It must not have been to delete a cell, just deleting 
something else in a function that defined a function.  Ah well.

>SyntaxError: can not delete variable 'foo' referenced in nested scope

Interestingly, it gives me a different error in IDLE: "unsupported operand 
type(s) for -: 'NoneType' and 'int'"

>Since foo() could escape bar, i.e. become reachable outside of bar(), we
>don't allow you to unbind foo.

So do this instead:

foo = None