Python中的上下文变量
Python中的上下文变量对象是一种有趣的变量类型,它根据上下文返回变量的值。根据单线程或执行中的上下文,它可能有多个值。 contextvars 模块中的 ContextVar 类,用于在Python中声明和使用上下文变量。
注意:这在Python版本 >= 3.7 中受支持。
以下是声明复杂变量的简单语法:
Syntax: contextvars.ContextVar(name, default)
Parameter:
- name: Name of the variable which can be used for reference or debug process.
- default: Returns the value of this variable in particular context. If there is no value in the context then it will return the default value.
Return: contextvars class object.
注意:上下文变量应该总是在程序的顶部创建,而不是在程序的函数或中间块中。
以下是 ContextVar 类中定义的方法:
- get(): Returns the value of context variable in the particular context, if it does not contain any then It will return the default value provided if provided, else raise a lookup error.
- set(value): This method is called to set a new value provided as parameter to the context variable in the particular context it is called in.
- reset(token): This method resets the value of context variable to that of before ContextVar.set() was called in reference to token returned by set() method.
例子 :
Python3
# import module
import contextvars
# declaring the variable
# to it's default value
cvar = contextvars.ContextVar("cvar",
default = "variable")
print("value of context variable cvar: \n",
cvar.get())
# calling set method
token = cvar.set("changed")
print("\nvalue after calling set method: \n",
cvar.get())
# checking the type of token instance
print("\nType of object instance returned by set method: \n",
type(token))
# calling the reset method.
cvar.reset(token)
print("\nvalue after calling reset method: \n",
cvar.get())
Python3
import contextvars
# declaring the variable
cvar = contextvars.ContextVar("cvar", default = "variable")
# calling set function to get a token object
token = cvar.set("changed")
# token.var returns the ContextVar
# object through which token is generated.
print("ContextVar object though which token was generated: ")
print(token.var)
# As only one time set is called
# it should return token.MISSING.
print("\nAfter calling token.old_value : ")
print(token.old_value)
# Recalling set method again to
# test other side of token.old_value
token = cvar.set("changed_2")
print("\nPrinting the value set before set method called last : ")
print(token.old_value)
print("\nThe current value of context variable is : ")
print(cvar.get())
输出 :
value of context variable cvar:
variable
value after calling set method:
changed
Type of object instance returned by set method:
value after calling reset method:
variable
contextvars 中的令牌类:
令牌对象由 ContextVar.set() 方法返回,并且可以在 ContextVar.reset(token) 方法中作为参数重用,以将其值重置为之前的令牌上下文变量,如上所述。
以下是可与令牌对象一起使用的属性:
- Token.var:它返回用于创建此令牌的 ContextVar 对象,由 CotextVar.set() 方法返回。这具有只读属性,这是不可调用的。
- Token.old_value:设置为变量在调用 ContextVar.set() 方法之前所具有的值,因此生成了令牌。它是不可调用的,它具有只读属性。如果在调用之前未设置变量,则它指向 Token.MISSING。
- Token.MISSING:被 Token.old_value 用作标记。
例子 :
Python3
import contextvars
# declaring the variable
cvar = contextvars.ContextVar("cvar", default = "variable")
# calling set function to get a token object
token = cvar.set("changed")
# token.var returns the ContextVar
# object through which token is generated.
print("ContextVar object though which token was generated: ")
print(token.var)
# As only one time set is called
# it should return token.MISSING.
print("\nAfter calling token.old_value : ")
print(token.old_value)
# Recalling set method again to
# test other side of token.old_value
token = cvar.set("changed_2")
print("\nPrinting the value set before set method called last : ")
print(token.old_value)
print("\nThe current value of context variable is : ")
print(cvar.get())
输出 :
ContextVar object though which token was generated:
After calling token.old_value :
contextvars 中的上下文类:
contextvars 模块中的这个上下文类是上下文变量到它们的值的映射。这也可以称为手动上下文管理器。
以下是该类的一些方法:
- context(): creates an empty context with no values in it.
- get(): returns the value of current variable if assigned, otherwise returns the default value if given, otherwise returns None.
- keys(): returns the list of all variables in the contextvars object.
- items(): returns the list of tuples with two elements in each tuple, first the name of variable and second its value for all the variables present in contextvars object.
- len(): returns the number of variables present in contextvars object.
- values(): returns a list of values of all the variables present in contextvars object.
- iter(): returns an iterator object which iterates over all the variables present in our contextvars object.
- copy_context(): returns a shallow copy of current contextvars object.
- run(callable, *args, **kwargs): Executes the function callable(*args, **kwargs) in the context to which run method is called and it returns the result of the program in callable function.