python reference counting and exceptions

Andreas Huesgen andreas.huesgen at arcor.de
Tue Sep 12 14:37:45 EDT 2006


Hello,

I have a question refering python's reference counting/garbage 
collection in combination with thrown exceptions.

I'm very new to this mailinglist, so I hope, that this question has not 
been asked and answered before.

In c++, it is possible to write a locking system similar to the one below:


void myFunction()
{
	# create a resource lock. Locks some resource
	ResourceLock myLock;
	
	# the following line may throw an exception
	doStuff();
}


myLock is a stack variable which is destroyed as soon as the function is 
left (either by returning or because of an uncatched exception). As 
myLock is destroyed, the destructor will automatically unlock the resource.

The following python code has the same effect (at least on my system and 
my python implementation).


class MyLock(object):
     def __init__(self):
         print "MyLock.__init__"

     def __del__(self):
         print "MyLock.__del__"

def myFunction():
     print "prelock"
     lock = MyLock()
     print "postlock"

print "prefun"
try:
     myFunction()
except Exception, e:
     print str(e)
print "postfun"

output is:
prefun
prelock
MyLock.__init__
postlock
MyLock.__del__
postfun
MyLock.__init__
MyLock.__del__


However, when myFunction raises an exception, lock is not destroyed as 
soon as the function is exited but only at the end of the script


My question is: is there some reliable way to mimic the c++ code snipped 
above in python without adding a try-except-unlock-rethrow block around 
every peace of code that locks some resources.


Greets,

Andreas Huesgen



More information about the Python-list mailing list