contextvars
— 上下文变量
¶
此模块提供管理、存储及访问上下文本地状态的 API。
ContextVar
类用于声明和操控
上下文变量
。
copy_context()
函数和
Context
类应该用于管理异步框架当前上下文。
有状态上下文管理器应该使用上下文变量而不是
threading.local()
来阻止它们的状态意外泄漏到其它代码,当用于并发代码中时。
另请参阅 PEP 567 了解额外细节。
3.7 版新增。
contextvars.
ContextVar
(
name
[
,
*
,
default
]
)
¶
此类用于声明新的上下文变量,如:
var: ContextVar[int] = ContextVar('var', default=42)
要求 name 参数用于自省和调试用途。
可选仅关键词
default
参数的返回通过
ContextVar.get()
当在当前上下文中找不到变量值时。
重要:
Context Variables should be created at the top module level and never in closures.
Context
objects hold strong references to context variables which prevents context variables from being properly garbage collected.
名称
¶
变量的名称。这是只读特性。
3.7.1 版新增。
get
(
[
default
]
)
¶
Return a value for the context variable for the current context.
If there is no value for the variable in the current context, the method will:
return the value of the default argument of the method, if provided; or
return the default value for the context variable, if it was created with one; or
引发
LookupError
.
set
(
value
)
¶
Call to set a new value for the context variable in the current context.
要求 value argument is the new value for the context variable.
返回
Token
object that can be used to restore the variable to its previous value via the
ContextVar.reset()
方法。
reset
(
token
)
¶
Reset the context variable to the value it had before the
ContextVar.set()
that created the
token
was used.
例如:
var = ContextVar('var') token = var.set('new value') # code that uses 'var'; var.get() returns 'new value'. var.reset(token) # After the reset call the var has no value again, so # var.get() would raise a LookupError.
contextvars.
令牌
¶
令牌
对象的返回通过
ContextVar.set()
方法。可以将它们传递给
ContextVar.reset()
method to revert the value of the variable to what it was before the corresponding
set
.
Token.
var
¶
只读特性。指向
ContextVar
object that created the token.
Token.
old_value
¶
A read-only property. Set to the value the variable had before the
ContextVar.set()
method call that created the token. It points to
Token.MISSING
is the variable was not set before the call.
Token.
MISSING
¶
标记对象用于
Token.old_value
.
contextvars.
copy_context
(
)
¶
返回拷贝为当前
Context
对象。
The following snippet gets a copy of the current context and prints all variables and their values that are set in it:
ctx: Context = copy_context() print(list(ctx.items()))
The function has an O(1) complexity, i.e. works equally fast for contexts with a few context variables and for contexts that have a lot of them.
contextvars.
上下文
¶
映射
ContextVars
到它们的值。
Context()
creates an empty context with no values in it. To get a copy of the current context use the
copy_context()
函数。
上下文实现
collections.abc.Mapping
接口。
run
(
callable
,
*args
,
**kwargs
)
¶
执行
callable(*args, **kwargs)
code in the context object the
run
method is called on. Return the result of the execution or propagate an exception if one occurred.
Any changes to any context variables that callable makes will be contained in the context object:
var = ContextVar('var') var.set('spam') def main(): # 'var' was set to 'spam' before # calling 'copy_context()' and 'ctx.run(main)', so: # var.get() == ctx[var] == 'spam' var.set('ham') # Now, after setting 'var' to 'ham': # var.get() == ctx[var] == 'ham' ctx = copy_context() # Any changes that the 'main' function makes to 'var' # will be contained in 'ctx'. ctx.run(main) # The 'main()' function was run in the 'ctx' context, # so changes to 'var' are contained in it: # ctx[var] == 'ham' # However, outside of 'ctx', 'var' is still set to 'spam': # var.get() == 'spam'
方法引发
RuntimeError
when called on the same context object from more than one OS thread, or when called recursively.
copy
(
)
¶
返回上下文对象的浅拷贝。
var in context
返回
True
若
context
has a value for
var
set; return
False
否则。
context[var]
Return the value of the
var
ContextVar
variable. If the variable is not set in the context object, a
KeyError
被引发。
get
(
var
[
,
default
]
)
¶
返回值为
var
if
var
has the value in the context object. Return
default
otherwise. If
default
is not given, return
None
.
iter(context)
Return an iterator over the variables stored in the context object.
len(proxy)
Return the number of variables set in the context object.
keys
(
)
¶
Return a list of all variables in the context object.
值
(
)
¶
Return a list of all variables’ values in the context object.
项
(
)
¶
Return a list of 2-tuples containing all variables and their values in the context object.
Context variables are natively supported in
asyncio
and are ready to be used without any extra configuration. For example, here is a simple echo server, that uses a context variable to make the address of a remote client available in the Task that handles that client:
import asyncio import contextvars client_addr_var = contextvars.ContextVar('client_addr') def render_goodbye(): # The address of the currently handled client can be accessed # without passing it explicitly to this function. client_addr = client_addr_var.get() return f'Good bye, client @ {client_addr}\n'.encode() async def handle_request(reader, writer): addr = writer.transport.get_extra_info('socket').getpeername() client_addr_var.set(addr) # In any code that we call is now possible to get # client's address by calling 'client_addr_var.get()'. while True: line = await reader.readline() print(line) if not line.strip(): break writer.write(line) writer.write(render_goodbye()) writer.close() async def main(): srv = await asyncio.start_server( handle_request, '127.0.0.1', 8081) async with srv: await srv.serve_forever() asyncio.run(main()) # To test it you can use telnet: # telnet 127.0.0.1 8081