Use ContextVar for current worker #5517
Draft
+107
−9
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.
Progress towards #5485.
This was surprisingly simple and actually seems to work. Not sure yet what it breaks.
I was pleasantly surprised to find that Tornado
loop.add_callback
s,PeriodicCallback
s, etc. all play correctly with asyncio's built-in contextvar management. With that, just setting the contextvar during__init__
andstart
probably catches almost all cases, because all the long-running callbacks/coroutines (including comms) will inherit the context that's set when they're created. Where else should we add thisas_current_worker
decorator?This gives me confidence we'll be able to use the same pattern for a single current client contextvar as mentioned in #5467 (comment).
cc @crusaderky @fjetter
threading.local()
with ContextVar #5485pre-commit run --all-files