tags:

views:

163

answers:

1

If I do this:

def foo():
     a = SomeObject()

Is 'a' destroyed immediately after leaving foo? Or does it wait for some GC to happen?

+18  A: 

Yes and no. The object will get destroyed after you leave foo (as long as nothing else has a reference to it), but whether it is immediate or not is an implementation detail, and will vary.

In CPython (the standard python implementation), refcounting is used, so the item will immediately be destroyed. There are some exceptions to this, such as when the object contains cyclical references, or when references are held to the enclosing frame (eg. an exception is raised that retains a reference to the frame's variables.)

In implmentations like Jython or IronPython however, the object won't be finalised until the garbage collector kicks in.

As such, you shouldn't rely on timely finalisation of objects, but should only assume that it will be destroyed at some point after the last reference goes. When you do need some cleanup to be done based on the lexical scope, either explicitely call a cleanup method, or look at the new with statement in python 2.6 (available in 2.5 with "from __future__ import with_statement").

Brian
+1: The variable, `a` is in a namespace that's removed immediately. This is what decrements the reference counts. The variable exists in a stack-like structure. The underlying object doesn't.
S.Lott