call of __del__ non-deterministic in python 2.4 (cpython)?

Mathias Panzenboeck e0427417 at student.tuwien.ac.at
Wed Dec 13 18:45:25 EST 2006


Anthony Baxter wrote:
> On 12/13/06, Holger Joukl <Holger.Joukl at lbbw.de> wrote:
>> I did read this but didn't think it applied to my situation. I'm quite
>> sure that the refcount of the local variable is 1 before the local scope
>> is left.
>> So let me rephrase the question: Even if I can make sure that non of the
>> problematic situtions apply, might it _still_ happen that __del__ gets
>> called
>> after some other code has already been "entered"?
> 
> You shouldn't rely on __del__ being called exactly when you expect it,
> particularly in a threaded application. Make explicit cleanup calls,
> instead.

a nice way to do such things in python 2.5 is using the with statement. this ensures to call a
__exit__ (cleanup) function after a __enter__ function was called, no matter if there is a exception
or something other in between.

with open("foo.txt","w") as fp:
	fp.write("foo")

translates to:

mgr = open("foo.txt","w")

# well, in the case of files, __enter__ just returns self
fp = mgr.__enter__()

try:
	fp.write("foo")
finally:
	mgr.__exit__() # this calls fp.close()


this of course is a simplified translation of the with statement.
see more details here: http://www.python.org/dev/peps/pep-0343/

with is also cool for using it in combination with mutexes and similar stuff.
it would also be possible to write a transaction manager which calls commit() or abort()
automatically, so you can just write:

with new_transaction():
	# if do_stuff() returns, commit() will be called
	# if it raises an exception abort() will be called
	do_stuff()

But if you can't use python 2.5, there is no other way then:

try:
	do_stuff()
finally:
	cleanup()



More information about the Python-list mailing list