gh-128555: Add 'context' keyword parameter to Thread. by nascheme · Pull Request #128209 · python/cpython (original) (raw)
Edit: this PR has been revised to make the behavior dependent on the build of Python used. The free-threaded build defaults to inheriting the context of the caller of Thread.start()
. The default behavior can be overridden by an -X
var or by an environment variable. In the long term I think the behavior should be consistent between builds, both inheriting by default. The flag gives users of the default build an opt-in setting.
- Add the
sys.flags.thread_inherit_context
flag. - This flag is set to true by default on the free-threaded build and false otherwise. If the flag is true, starting a new thread using
threading.Thread
will, by default, use a copy of thecontextvars.Context
from the caller ofthreading.Thread.start
rather than using an empty context. - Add the
-X thread_inherit_context
command-line option andPYTHON_THREAD_INHERIT_CONTEXT
environment variable, which set thesys.flags.thread_inherit_context
flag. - Add the
context
keyword parameter tothreading.Thread
. It can be used to explicitly pass a context value to be used by a new thread. - Make the
_contextvars
module built-in.
This was motivated by making the warnings
module work more reliably when threads and asyncio are used in combination with catch_warnings
. I'm working on a PR that will make warnings
use a contextvar for the filtering state.
Making new threads inherit context is not a new idea, it was suggested around the 3.10 release timeframe, gh-86981.
📚 Documentation preview 📚: https://cpython-previews--128209.org.readthedocs.build/