contextvars
--- 情境變數¶
This module provides APIs to manage, store, and access context-localstate. TheContextVar
class is used to declareand work withContext Variables. Thecopy_context()
function and theContext
class should be used tomanage the current context in asynchronous frameworks.
Context managers that have state should use Context Variablesinstead ofthreading.local()
to prevent their state frombleeding to other code unexpectedly, when used in concurrent code.
額外資訊請見PEP 567。
在 3.7 版被加入.
Context Variables¶
- classcontextvars.ContextVar(name[,*,default])¶
This class is used to declare a new Context Variable, e.g.:
var:ContextVar[int]=ContextVar('var',default=42)
The requiredname parameter is used for introspection and debugpurposes.
The optional keyword-onlydefault parameter is returned by
ContextVar.get()
when no value for the variable is foundin the current context.Important: Context Variables should be created at the top modulelevel and never in closures.
Context
objects hold strongreferences to context variables which prevents context variablesfrom being properly garbage collected.- name¶
這個變數的名稱。這是一個唯讀屬性。
在 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 thedefault 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 currentcontext.
The requiredvalue argument is the new value for the contextvariable.
Returns a
Token
object that can be usedto restore the variable to its previous value via theContextVar.reset()
method.
- reset(token)¶
Reset the context variable to the value it had before the
ContextVar.set()
that created thetoken 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.
- classcontextvars.Token¶
Token objects are returned by the
ContextVar.set()
method.They can be passed to theContextVar.reset()
method to revertthe value of the variable to what it was before the correspondingset.- var¶
A read-only property. Points to the
ContextVar
objectthat created the token.
- old_value¶
A read-only property. Set to the value the variable had beforethe
ContextVar.set()
method call that created the token.It points toToken.MISSING
if the variable was not setbefore the call.
- MISSING¶
A marker object used by
Token.old_value
.
Manual Context Management¶
- contextvars.copy_context()¶
Returns a copy of the current
Context
object.The following snippet gets a copy of the current context and printsall variables and their values that are set in it:
ctx:Context=copy_context()print(list(ctx.items()))
The function has anO(1) complexity, i.e. works equally fast forcontexts with a few context variables and for contexts that havea lot of them.
- classcontextvars.Context¶
A mapping of
ContextVars
to their values.Context()
creates an empty context with no values in it.To get a copy of the current context use thecopy_context()
function.Each thread has its own effective stack of
Context
objects. Thecurrent context is theContext
object at the top of thecurrent thread's stack. AllContext
objects in the stacks areconsidered to beentered.Entering a context, which can be done by calling its
run()
method, makes the context the current context by pushing it onto the top ofthe current thread's context stack.Exiting from the current context, which can be done by returning from thecallback passed to the
run()
method, restores the currentcontext to what it was before the context was entered by popping the contextoff the top of the context stack.Since each thread has its own context stack,
ContextVar
objectsbehave in a similar fashion tothreading.local()
when values areassigned in different threads.Attempting to enter an already entered context, including contexts entered inother threads, raises a
RuntimeError
.After exiting a context, it can later be re-entered (from any thread).
Any changes to
ContextVar
values via theContextVar.set()
method are recorded in the current context. TheContextVar.get()
method returns the value associated with the current context. Exiting acontext effectively reverts any changes made to context variables while thecontext was entered (if needed, the values can be restored by re-entering thecontext).Context implements the
collections.abc.Mapping
interface.- run(callable,*args,**kwargs)¶
Enters the Context, executes
callable(*args,**kwargs)
, then exits theContext. Returnscallable's return value, or propagates an exception ifone occurred.舉例來說:
importcontextvarsvar=contextvars.ContextVar('var')var.set('spam')print(var.get())# 'spam'ctx=contextvars.copy_context()defmain():# 'var' was set to 'spam' before# calling 'copy_context()' and 'ctx.run(main)', so:print(var.get())# 'spam'print(ctx[var])# 'spam'var.set('ham')# Now, after setting 'var' to 'ham':print(var.get())# 'ham'print(ctx[var])# 'ham'# 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:print(ctx[var])# 'ham'# However, outside of 'ctx', 'var' is still set to 'spam':print(var.get())# 'spam'
- copy()¶
Return a shallow copy of the context object.
- varincontext
Return
True
if thecontext has a value forvar set;returnFalse
otherwise.
- context[var]
Return the value of thevar
ContextVar
variable.If the variable is not set in the context object, aKeyError
is raised.
- get(var[,default])¶
Return the value forvar ifvar has the value in the contextobject. Returndefault otherwise. Ifdefault is not given,return
None
.
- iter(context)
Return an iterator over the variables stored in the contextobject.
- len(proxy)
Return the number of variables set in the context object.
- keys()¶
Return a list of all variables in the context object.
- values()¶
Return a list of all variables' values in the context object.
- items()¶
Return a list of 2-tuples containing all variables and theirvalues in the context object.
對 asyncio 的支援¶
Context variables are natively supported inasyncio
and areready to be used without any extra configuration. For example, hereis a simple echo server, that uses a context variable to make theaddress of a remote client available in the Task that handles thatclient:
importasyncioimportcontextvarsclient_addr_var=contextvars.ContextVar('client_addr')defrender_goodbye():# The address of the currently handled client can be accessed# without passing it explicitly to this function.client_addr=client_addr_var.get()returnf'Good bye, client @{client_addr}\r\n'.encode()asyncdefhandle_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()'.whileTrue:line=awaitreader.readline()print(line)ifnotline.strip():breakwriter.write(b'HTTP/1.1 200 OK\r\n')# status linewriter.write(b'\r\n')# headerswriter.write(render_goodbye())# bodywriter.close()asyncdefmain():srv=awaitasyncio.start_server(handle_request,'127.0.0.1',8081)asyncwithsrv:awaitsrv.serve_forever()asyncio.run(main())# To test it you can use telnet or curl:# telnet 127.0.0.1 8081# curl 127.0.0.1:8081