pep-567: ContextVar.reset() raises a RuntimeErorr on already used tokens (#542)

This commit is contained in:
Yury Selivanov 2018-01-17 12:42:29 -05:00 committed by GitHub
parent c25174f10d
commit 07e87ce3d3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 11 additions and 9 deletions

View File

@ -174,14 +174,16 @@ not set)::
# After reset: var.get(None) is None,
# i.e. 'var' was removed from the current context.
``ContextVar.reset()`` method is idempotent and can be called
multiple times on the same Token object: second and later calls
will be no-ops. The method raises a ``ValueError`` if:
The ``ContextVar.reset()`` method raises:
* it is called with a token object created by another variable; or
* a ``ValueError`` if it is called with a token object created
by another variable;
* the current ``Context`` object does not match the one where
the token object was created.
* a ``ValueError`` if the current ``Context`` object does not match
the one where the token object was created;
* a ``RuntimeError`` if the token object has already been used once
to reset the variable.
contextvars.Token
@ -463,6 +465,9 @@ directly::
return Token(ts.context, self, old_value)
def reset(self, token):
if token._used:
raise RuntimeError("Token has already been used once")
if token._var is not self:
raise ValueError(
"Token was created by a different ContextVar")
@ -472,9 +477,6 @@ directly::
raise ValueError(
"Token was created in a different Context")
if token._used:
return
if token._old_value is Token.MISSING:
ts.context._data = data.delete(token._var)
else: