bpo-40320: Added support for manipulating context in asyncio tasks #26664
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Proposal and sample implementation to address https://bugs.python.org/issue40320 and extend behavior a bit to get parity with what's available in synchronous code.
Makes three public API changes
context
keyword parameter to the asyncio.Task constructor. When given this will be the contextvars.Context the task will be run in. When not specified the existing default of copying the callers context will still be used.asyncio.run
to pass additional keyword arguments to the task constructor. This isn't really necessary but seemed like a nice (and it also seemed like it would be nice if you could specify the name of the task created byasyncio.run
).asyncio.run_in_context
that functions in an analagous manner tocontextvars.Context.run
. It will manage swapping out the coroutine associated with the task while the passed coroutine is executing within the task.asyncio.run_in_context
is implemented by assing an additional private methodTask._set_context
that can change the context associated with a task (although a yield out of the task step function is required before the new context is active).This is all to better support contextvars in an asyncio context. Without this support it was impossible to run async code in a different context without creating a new task. It was also impossible to create a task using any context other than a copy of the calling context (i.e. the context used was always a copy).
Example Usage
https://bugs.python.org/issue40320