GH-96704: Add task.get_context(), use it in call_exception_handler()#96756
Uh oh!
There was an error while loading. Please reload this page.
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.
The point here is for
call_exception_handler()to make an effort to run the exception handler in the correct task context (contextvars.Context), if it is called on behalf of a task.The easiest way seems to be to retrieve the task context from the task passed into the context
dictthat's being passed tocall_exception_handler(). This doesn't always exist, and becauseTaskinherits fromFuture, it may be stored under either a"task"key or a"future"key. So try both.We then need to retrieve the
contextvars.Contextfrom the task, for which I have added aget_context()method to theTaskclass (analogous toget_name()). It is possible that the task doesn't have this method (e.g. if the loop is using a 3rd party task implementation that doesn't yet support this new method).Only if
get_context()exists and returns something that has arun()method do we run the exception handler using thatcontextvars.Context.run()method. Otherwise we use the defaultcontextvars.Context.We only do this for an exception handler set by the user; the default exception handler should not be interested in the context. (This is because I'm lazy, there are two calls to it and I don't want to bother giving those the same treatment -- we can reconsider if you think the logger might also be interested in the
contextvars.Context.)PS. It's unfortunate that
call_exception_handler()has a parameter namedcontextthat is adict, not acontextvars.Context. But nothing we can do it now (this API probably predatescontextvars).