This PEP proposes a way to protect Python code from being interrupted inside a finally clause or during context manager cleanup.

Further exploration of the concepts covered in this PEP has been deferred for lack of a current champion interested in promoting the goals of the PEP and collecting and incorporating feedback, and with sufficient available time to do so effectively.

Python has two nice ways to do cleanup. One is a finally statement and the other is a context manager (usually called using a with statement). However, neither is protected from interruption by KeyboardInterrupt or GeneratorExit caused by generator.throw() . For example:

lock.acquire() try: print('starting') do_something() finally: print('finished') lock.release()

If KeyboardInterrupt occurs just after the second print() call, the lock will not be released. Similarly, the following code using the with statement is affected:

from threading import Lock class MyLock: def __init__(self): self._lock_impl = Lock() def __enter__(self): self._lock_impl.acquire() print("LOCKED") def __exit__(self): print("UNLOCKING") self._lock_impl.release() lock = MyLock() with lock: do_something

If KeyboardInterrupt occurs near any of the print() calls, the lock will never be released.