[Python-Dev] PEP 567 (contextvars) idea: really implement the current context

Victor Stinner victor.stinner at gmail.com
Wed Jan 3 21:12:10 EST 2018


Victor:
> I modified Context mapping API to use the context variables from the
> current thread state if it's the current thread state.

Oops, I mean: "if it's the current context".

Nathaniel:
"""
- BUT it doesn't allow mutation through the MutableMapping interface;
instead, the only way to mutate it is by calling Context.run and then
ContextVar.set(). Funneling all 'set' operations through a single
place makes it easier to do clever caching tricks, and it lets us
avoid dealing with operations that we don't want here (like 'del')
just because they happen to be in the MutableMapping interface.
"""

If a context knows that it's the current context, Context.set() can
delegate the change to ContextVar.set(), since Context access directly
the thread local storage in this case (with my suggested changes), and
so the optimization is kept.

If the context is not the current context, the cache doesn't have to
be invalidated. Moreover, PyContext_Enter() and PyContext_Exit()
already increases ts->contextvars_stack_ver which indirectly
invalidates cached values.

Nathaniel: Would you be ok to implement the MutableMapping API if the
optimization is kept? "del context[var]" would raise a
TypeError('Context' object doesn't support item deletion) exception,
as it does currently.

Victor


More information about the Python-Dev mailing list