469,366 Members | 2,286 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,366 developers. It's quick & easy.

python reference counting and exceptions


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
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"
except Exception, e:
print str(e)
print "postfun"

output is:
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.

Andreas Huesgen
Sep 12 '06 #1
0 831

This discussion thread is closed

Replies have been disabled for this discussion.

By using this site, you agree to our Privacy Policy and Terms of Use.