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.
This is a proposal to fix #2 in Approach 2, with patching code to achieve context copying on task creation, please see separate commits in this PR. Regarding context copying/inheriting:
contextvars
with this PR, allcreate_task()
calls of event loops which went through eitherasyncio.get_event_loop()
,asyncio.new_event_loop()
orasyncio.set_event_loop()
would implicitly do an extra context copy, and use it as task context.contextvars
before initializing event loop policies or creating event loops, and all tasks created by automatically patched loops could inherit the context on creation.get_event_loop_policy()
shall no longer return the policy passed toset_event_loop_policy()
with this PR - a wrapper policy is returned. Although the wrapper works in the same way as the original policy,get_event_loop_policy().policy
should be used if original policy instance is required.Other than patching, it is also possible to use
get_task_factory()
andset_task_factory()
to achieve the same result, as demonstrated here. Pros and cons:enable_inherit(loop)
for any loop in use.At last, the reason for using Approach 2 of #2 is:
Future
whose_loop
is underlying loop, but when using the wrapper loop to e.g.gather()
it checksfuture._loop is loop
and fails. Or vise versa. AlsoTask
code needs to be backported anyway.)UPDATE: This is now under testing in practice as
aiocontextvars
0.2 in GINO and possibly some other projects.