Python contextvars.Tokens

Python contextvars.Tokens


In python, each logical line is broken into a succession of elementary lexical parts.
These parts are known as tokens. Every token compares to a substring of the logical

contextvars.Token is an opaque object that ought to be utilized to reestablish the ContextVar to
its past value, or to eliminate it from the context if the variable was not set
previously. It can be created only by calling ContextVar.set().

For debug and introspection purposes it has:

- a read-only attribute Token.var highlighting the variable that made the token

- a read-only attribute Token.old_value set to the value the variable had before

the set() call, or to Token.MISSING if the variable wasn't set previously.

Token.MISSING is a marker object used by Token.old_value.

Example code for the above:

import contextvars

cvar = contextvars.ContextVar(
"Cppsecrets", default="variable")

# calling set function
to get a token object

token = cvar.set("Cppsecrets")


print("\nCalling token.old_value ")


# token.MISSING should
be return as it's called only 1 time

token = cvar.set("")

print("\nNow Printing the old Value : ")


print("\nThe current value of context variable is : ")


Output for the above code is as below: 

<ContextVar name='Cppsecrets' default='variable' at 0x00000247DA6714F0>

Calling token.old_value 


Now Printing the old Value : 


The current value of context variable is :

Process finished with exit code 0

<< PREV                                                                                                                                       NEXT>>