Best way to handle exceptions with try/finally
Roy Smith
roy at panix.com
Wed May 24 08:11:06 EDT 2006
In article <1148457332.582609.98490 at 38g2000cwa.googlegroups.com>,
"Maxim Sloyko" <m.sloyko at gmail.com> wrote:
> I guess the following standard method will help :
>
> class MyLocker(object):
> def __init__(self, lock):
> self.lock = lock
> self.lock.acquire()
>
> def __del__(self):
> self.lock.release()
>
> Then whenever you need to acquire a lock:
> templock = MyLocker(self.__mutex)
>
> del templock # will release the lock (provided you didn't create an
> extra link to this object)
Warning! Danger, Will Robinson! Evil space aliens are trying to write C++
in Python! Quick, we must get back to the ship before they eat our brains!
The problem here is that there is no guarantee that __del__() will get
called at any predictable time (if at all). C++ uses deterministic object
destruction. Python doesn't destroy (finalize?) objects until the garbage
collector runs.
See PEP-343 (http://www.python.org/dev/peps/pep-0343/) for the new "with"
statement which should solve problems like this. If I understand things
right, "with" will be included in Python-2.5, which is due out Real Soon
Now.
More information about the Python-list
mailing list