[Python-Dev] Object finalization for local (ie function) scop es

Jewett, Jim J jim.jewett at eds.com
Mon Jun 14 11:43:53 EDT 2004

I suspect people are talking about slightly different things.
I'll try to make my understanding very explicit, so that 
people can jump on the parts they disagree with.

(1)  Python does not guarantee that it will clean up for you.

If an object has a __del__ method, then this method will be
run when the object is finalized -- but python might decide
to never finalize the object.  For example, if there are
two objects in a cycle, and both have a __del__ method, then
python may decide to make them immortal, so that it doesn't
have to decide which __del__ to run first.

(2)  It is fairly common to have a resource which should be
closed/released when you are done.  (Example:  a file).  

Normally, the garbage collector will do this for you -- it 
might even do so in all your tests, but not in production.

If you want to *ensure* that your files are flushed and
closed, you have to do it yourself, because python might 
choose not to collect them, even though it could.

This is bug-prone.  

	(a)  It is easy to forget (and the problem may not
	show up in tests, because the garbage collection will 
	*usually* work).

	(b)  Calling a finalizer (such as close) explicitly 
	means you can call it before all references are truly

(3)  The closest thing there is to a safe idiom today is to
emulate lisp's with-open-* macros using try/finally.

		f = open("filename")
	# if you do catch exceptions, then finally will have to
	# be replaced with a bare except and a reraise, plus an 
	# else clause

(4)  Proponents would like a way of saying "objects like this
should *always* get their finalizer called".  In return, they're 
willing to say "this is a temporary object that will not be 
returned from the local scope."  If you replaced




then any such objects created in f should have their __del__
methods run now.  Even if they do appear in cycles.  Even if
they are referenced by an uncollectable object, such as an old
extension class.

(5)  As proposed, it would be the user's responsibilibity to 
ensure that running __del__ was safe.  In return, python would
guarantee to actually do it, even if garbage collection is
turned off.


More information about the Python-Dev mailing list