From 3b59266d432ecc1136eb2599f9cf5fc41b71b16f Mon Sep 17 00:00:00 2001 From: Yury Selivanov Date: Tue, 12 Dec 2017 23:42:13 -0500 Subject: [PATCH] pep-567: Add a Token section to the Specification (#509) --- pep-0567.rst | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/pep-0567.rst b/pep-0567.rst index c3fb17f5e..30367badb 100644 --- a/pep-0567.rst +++ b/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.)