You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
[(<ContextVar name='one' at 0x107312930>, 1)]
1
[(<ContextVar name='one' at 0x107312930>, 1)]
("<Token var=<ContextVar name='one' at 0x107312930> at 0x107303480> was created in a different Context",)
In finally block it's not possible to manually reset the contextvars
Yes this is expected, because the async generator finalization is triggered by the garbage collector, where asyncio uses sys.set_asyncgen_hooks() to aclose the async generator in a new task. See https://peps.python.org/pep-0525/#finalization
If you want to ensure finalization in the same context use
If an asynchronous generator happens to exit early by break, the caller task being cancelled, or other exceptions, the generator’s async cleanup code will run and possibly raise exceptions or access context variables in an unexpected context–perhaps after the lifetime of tasks it depends, or during the event loop shutdown when the async-generator garbage collection hook is called. To prevent this, the caller must explicitly close the async generator by calling aclose() method to finalize the generator and ultimately detach it from the event loop.
This pattern ensures that the generator’s async exit code is executed in the same context as its iterations (so that exceptions and context variables work as expected, and the exit code isn’t run after the lifetime of some task it depends on).
Activity
graingert commentedon May 11, 2024
Yes this is expected, because the async generator finalization is triggered by the garbage collector, where asyncio uses sys.set_asyncgen_hooks() to aclose the async generator in a new task. See https://peps.python.org/pep-0525/#finalization
If you want to ensure finalization in the same context use
graingert commentedon May 11, 2024
See also https://docs.python.org/3/reference/expressions.html#asynchronous-generator-functions
And https://docs.python.org/3/library/contextlib.html#contextlib.aclosing
graingert commentedon May 11, 2024
I'm going to close this, as working as documented