[Python-Dev] PEP 567 v3 (original) (raw)

Nick Coghlan ncoghlan at gmail.com
Wed Jan 17 00:45:03 EST 2018


On 17 January 2018 at 11:27, Nathaniel Smith <njs at pobox.com> wrote:

On Tue, Jan 16, 2018 at 2:44 PM, Yury Selivanov <yselivanov.ml at gmail.com> wrote:

4. ContextVar.reset(token) now raises a ValueError if the token was created in a different Context. A minor bit of polish: given that Token objects have to track the associated ContextVar anyway, I think it'd be cleaner if instead of doing: token = cvar.set(...) cvar.reset(token) we made the API be: token = cvar.set(...) token.reset()

As a counterpoint to this, consider the case where you're working with two cvars:

token1 = cvar1.set(...)
token2 = cvar2.set(...)
...
cvar1.reset(token1)
...
cvar2.reset(token2)

At the point where the resets happen, you know exactly which cvar is being reset, even if you don't know where the token was created.

With reset-on-the-token, you're entirely reliant on variable naming to know which ContextVar is going to be affected:

token1 = cvar1.set(...)
token2 = cvar2.set(...)
...
token1.reset() # Resets cvar1
...
token2.reset() # Resets cvar2

If someone really does want an auto-reset API, it's also fairly easy to build atop the more explicit one:

def set_cvar(cvar, value):
    token = cvar.set(value)
    return functools.partial(cvar.reset, token)

reset_cvar1 = set_cvar(cvar1, ...)
...
reset_cvar1()

Cheers, Nick.

-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia



More information about the Python-Dev mailing list