ContextVars in async context

Dieter Maurer dieter at handshake.de
Wed Dec 21 12:16:14 EST 2022


Marce Coll wrote at 2022-12-20 22:09 +0100:
>Hi python people, hope this is the correct place to ask this!
>
>For a transactional async decorator I'm building I am using contextvars in order to know when a transaction is open in my current context.
>
>My understanding is that if given the following call stack
>
>A
>|- B
>|  |- C
>|- D
>   |- E
>
>If you set a context var at A with value 1, and then override it at B with value 2, then A, D and E will see value 1 and B and C will se value 2. Very similar (although a bit more manual) than dynamic scopes in common lisp.

This is not the way I understand context variables.
In my view (--> PEP 0567), the context is the coroutine not the call stack.
This means: all calls in the same coroutine share the same context
variables. In your example, if `B` overrides the context variable, then
all later calls in this coroutine will see the overridden value.


More information about the Python-list mailing list