[issue29988] with statements are not ensuring that __exit__ is called if __enter__ succeeds

Gregory P. Smith report at bugs.python.org
Fri Sep 27 17:20:31 EDT 2019


Gregory P. Smith <greg at krypto.org> added the comment:

As a note on the general pattern, a user at work diagnosed a ^C problem in their code when running on 2.7 to be due to Queue.get's

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

Pattern, with the KeyboardInterrupt triggering after acquire() but before the try is entered.  so release() is never called.

A try finally pattern that probably alleviates this by entering the try block first might look like:

try:
  acquire()
  ...
finally:
  try:
    release()
  except ThreadError:
    pass  # interrupted before acquire() succeeded.


It'd be a shame if any with statements lock acquisition context managers need to be turned into that, but I _believe_ it'd be a viable workaround for the time being if this race is found to be biting anyone.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue29988>
_______________________________________


More information about the Python-bugs-list mailing list