python / cpython

The Python programming language
https://www.python.org
Other
62.9k stars 30.13k forks source link

Improved signal handling initialization for embedded Python #111400

Open whitevegagabriel opened 11 months ago

whitevegagabriel commented 11 months ago

Feature or enhancement

Proposal:

If Python has been initialized via

Py_InitializeEx(0);

then importing signal as

import signal

should by default skip setting up signal handlers.


I understand that this proposal is not a small ask. Currently, the flag to skip signals is used to determine whether to init signal. If someone calls import signal later on, then the user has shown clear intent to diverge from the initial state of skipping signal handling setup in Python.

However, the problem is that while I can avoid calling import signal in this embedded environment, it is hard to avoid it as a transitive dependency.

For example, the library asyncio calls import signal.

Of course, I can change my signal handler from SIG_DFL to anything else. However, if I do that, then the usefulness of Py_InitializeEx(0); is diminished.

Ultimately, I think it is more intuitive to think that, if I initialize Python via Py_InitializeEx(0), calling import signal will also skip setting up signal handlers.

And for SIGINT, for example, users would still have the freedom to call signal.signal(signal.SIGINT, signal.default_int_handler) if they really want KeyboardInterrupt.

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

https://discuss.python.org/t/asyncio-skipping-signal-handling-setup-during-import-for-python-embedded-context/37054

BTOdell commented 8 months ago

For embedded Python, it makes even more sense (to me) to have a way to completely disable the signal module. This would allow a host environment to be confident that code running in the embedded environment cannot disrupt the host environment's signal handling.

This train of thought could go even further: Classify and disable all modules/functions that could disrupt the host environment (e.g. sys.exit, entire subprocess module?, etc). I know this is out of scope for this feature request, but just thinking out loud here.