Python complaints
Gordon McMillan
gmcm at hypernet.com
Thu Nov 25 08:16:12 EST 1999
Toby J Sargeant wrote:
> Just throwing this up in the air, and seeing what comes back...
>
> class Acquire:
> def __init__(self,lock):
> self.lock=lock
> lock.acquire()
>
> def __del__(self):
> self.lock.release()
>
> def function(mutex):
> _a=Acquire(mutex)
> # do stuff.
>
> It relies on Acquire.__del__() being called as soon as _a goes
> out of scope, but that doesn't seem likely to change for the
> moment. (Of course doing this in JPython is a recipe for
> disaster... or at least extreme inefficiency)
>
> It also has the advantage that you can exit the function in many
> ways (including by exception), and the lock will be released
> regardless.
Most unfortunately, exiting by exception will foul you up
because the traceback will have a reference to the Acquire
instance. You can clear it when you catch the exception, but
since the consequences of forgetting to do that are both
disastrous and mysterious, I think this idiom is best left to
C++ (where I use it all the time).
- Gordon
More information about the Python-list
mailing list