Question

I'm working on an open source intermediate Python book and going over a number of PEPs. In PEP310, there is an old proposal for "with" statements. The proposal was eventually rejected, but the following statement struck me: "Another common error is to code the "acquire" call within the try block, which incorrectly releases the lock if the acquire fails."

Could someone elaborate on how putting the acquire inside the try changes things? To my understanding, acquire calls in Python just return a boolean indicating whether the lock was successfully acquired, so how does putting it inside a try block change things?

Was it helpful?

Solution

I believe this is what it's referring to:

try:
    lock.acquire()
finally:
    lock.release()

If acquire() raises an exception, release() will be called, even though acquire() didn't succeed. Calling release() on a lock which isn't currently locked may raise another exception, i.e. an exception that is only indirectly related to the root of the problem.

The correct way to write the block would either be to use with, or:

lock.acquire()
try:
    ...
finally:
    lock.release()

You should always code to cater for exceptions, regardless of whether the documentation suggests that a call raises one or not. There's nothing to stop the behaviour changing in future.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top