Hi Yury,

thanks for the quick reply.

Yury Selivanov wrote:

> Adding context manager protocol support to contextvars.Token was
> considered when PEP 567 was discussed.  There wasn't a strong argument
> against that; however we decided not to immediately add it because
> context variables is a relatively low-level API.  In you case, you can
> simply wrap a ContextVar in a context manager:
>
> (...)

I'm aware of this possibility, however it is not suitable for the use
case that I have in mind (configuration variables), because it requires
too much code for each variable.

Of course one could wrap your example inside a factory function, but
that's unwieldy as well, since it requires keeping track of one context
manager for each context variable:

def factory(name):
    _setting = contextvars.ContextVar(name)

    @contextlib.contextmanager
    def setting(value):
      tok = _setting.set(value)
      try:
        yield
      finally:
        _setting.reset(tok)

    return _setting, setting

One possibility to imlement this cleanly and efficiently without
modifying the standard library module would be to derive classes from
ContextVar and from Token, but this is not possible.

So it seems to me that if the use of context variables as explicit dynamically
bound variables for library configuration is considered interesting, one
should think about adding __enter__ and __exit__ to contextvars.Token.

By the way, contexts being implemented as immutable dictionaries implies
one copy of a dictionary per call to the set method.  That in turn means
that using hundreds of context variables (a large library could easily
have that many configuration variables) might not be a good idea.  Is
this correct?

A final, unrelated comment: I find the use of the word "context" in the
standard library for both context managers and context variables (and
related to them "contexts") needlessly confusing.  I suggest clearly
explaining their independence at the top of the documentation of either
module.

Attachment: signature.asc
Description: PGP signature

Python-Ideas mailing list -- python-dev(a)python.org
To unsubscribe send an email to python-ideas-leave(a)python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/

Reply via email to