[New-bugs-announce] [issue31388] Provide a way to defer SIGINT handling in the current thread

Nick Coghlan report at bugs.python.org
Thu Sep 7 16:03:25 EDT 2017


New submission from Nick Coghlan:

As discussed in issue 29988, it's currently difficult to write completely robust cleanup code in Python, as the default SIGINT handler may lead to KeyboardInterrupt being raised as soon as *any* Python code starts executing in the main thread, even when that Python code is part of:

- a finally block
- an __exit__ method
- a __del__ method
- a weakref callback
- a trace hook
- a profile hook
- a pending call callback

Issue 29988 proposes a way to adjust with statements to ensure that __exit__ at least starts executing if __enter__ returned successfully, but that's only sufficient to ensure robust resource cleanup if the __exit__ method is implemented in C and never calls back in to any operation that starts executing Python code.

Currently, the "best" option for ensuring cleanup code isn't interrupted is to outright ignore SIGINT while the cleanup code is running:

    old_handler = signal.getsignal(signal.SIGINT)
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    try:
        ... # Cleanup code
    finally:
        signal.signal(signal.SIGINT, old_handler)

Fortunately, most folks aren't willing to do this, but it does suggest a potential pattern for temporarily *deferring* SIGINT handling: adding a "deferred" attribute to the entries in the array that tracks incoming signals, and providing some C level decorators and context managers for manipulating that state.

----------
components: Interpreter Core
messages: 301622
nosy: gregory.p.smith, ncoghlan, njs
priority: normal
severity: normal
stage: needs patch
status: open
title: Provide a way to defer SIGINT handling in the current thread
type: enhancement
versions: Python 3.7

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


More information about the New-bugs-announce mailing list