Python contextvars.Tokens














































Python contextvars.Tokens



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
line.

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(token.var)

print("\nCalling token.old_value ")

print(token.old_value)

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

token = cvar.set("Cppsecrets.com")

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

print(token.old_value)

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

print(cvar.get())


Output for the above code is as below: 

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


Calling token.old_value 

<Token.MISSING>


Now Printing the old Value : 

Cppsecrets


The current value of context variable is : 

Cppsecrets.com


Process finished with exit code 0

<< PREV                                                                                                                                       NEXT>>


Comments