pep-567: Add a Token section to the Specification (#509)
This commit is contained in:
parent
29ab20e269
commit
3b59266d43
31
pep-0567.rst
31
pep-0567.rst
|
@ -133,10 +133,11 @@ the context variable in the current ``Context``::
|
|||
# Set the variable 'var' to 1 in the current context.
|
||||
var.set(1)
|
||||
|
||||
``contextvars.Token`` is an opaque object that should be used to
|
||||
restore the ``ContextVar`` to its previous value, or remove it from
|
||||
the context if it was not set before. The ``ContextVar.reset(Token)``
|
||||
is used for that::
|
||||
``ContextVar.reset(token)`` is used to reset the variable in the
|
||||
current context to the value it had before the ``set()`` operation
|
||||
that created the ``token``::
|
||||
|
||||
assert var.get(None) is None
|
||||
|
||||
token = var.set(1)
|
||||
try:
|
||||
|
@ -144,10 +145,24 @@ is used for that::
|
|||
finally:
|
||||
var.reset(token)
|
||||
|
||||
assert var.get(None) is None
|
||||
|
||||
``ContextVar.reset()`` method is idempotent and can be called
|
||||
multiple times on the same Token object: second and later calls
|
||||
will be no-ops.
|
||||
|
||||
|
||||
contextvars.Token
|
||||
-----------------
|
||||
|
||||
``contextvars.Token`` is an opaque object that should be used to
|
||||
restore the ``ContextVar`` to its previous value, or remove it from
|
||||
the context if the variable was not set before. It can be created
|
||||
only by calling ``ContextVar.set()``.
|
||||
|
||||
For debug and introspection purposes it has a read-only attribute
|
||||
``Token.var`` pointing to the variable that created the token.
|
||||
|
||||
Having the ``ContextVar.set()`` method returning a ``Token`` object
|
||||
and the ``ContextVar.reset(token)`` method, allows context variables
|
||||
to be removed from the context if they were not in it before the
|
||||
|
@ -159,10 +174,6 @@ method, which is incompatible with chained contexts design of
|
|||
(at least for Python 3.7) in case there is demand to support
|
||||
context variables in generators and asynchronous generators.
|
||||
|
||||
``ContextVar`` design allows for a fast implementation of
|
||||
``ContextVar.get()``, which is particularly important for modules
|
||||
like ``decimal`` and ``numpy``.
|
||||
|
||||
|
||||
contextvars.Context
|
||||
-------------------
|
||||
|
@ -428,6 +439,10 @@ points to a ``_ContextData`` object::
|
|||
self._old_value = old_value
|
||||
self._used = False
|
||||
|
||||
@property
|
||||
def var(self):
|
||||
return self._var
|
||||
|
||||
|
||||
(The ``_NO_VALUE`` is an internal marker object that will not be
|
||||
part of the public API.)
|
||||
|
|
Loading…
Reference in New Issue