contextvars —- Context Variables


This module provides APIs to manage, store, and access context-localstate. The ContextVar class is used to declareand work with Context Variables. The copy_context()function and the Context class should be used tomanage the current context in asynchronous frameworks.

Context managers that have state should use Context Variablesinstead of threading.local() to prevent their state frombleeding to other code unexpectedly, when used in concurrent code.

See also PEP 567 for additional details.

3.7 新版功能.

Context Variables

  • class contextvars.ContextVar(name[, *, default])
  • This class is used to declare a new Context Variable, e.g.:
  1. var: ContextVar[int] = ContextVar('var', default=42)

The required name parameter is used for introspection and debugpurposes.

The optional keyword-only default parameter is returned byContextVar.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
  • The name of the variable. This is a read-only property.

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:

  1. -

return the value of the default argument of the method,if provided; or

  1. -

return the default value for the context variable,if it was created with one; or

  1. -

raise a LookupError.

  • set(value)
  • Call to set a new value for the context variable in the currentcontext.

The required value 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 theContextVar.set() that created the token was used.

例如

  1. var = ContextVar('var')
  2.  
  3. token = var.set('new value')
  4. # code that uses 'var'; var.get() returns 'new value'.
  5. var.reset(token)
  6.  
  7. # After the reset call the var has no value again, so
  8. # var.get() would raise a LookupError.
  • class contextvars.Token
  • Token objects are returned by the ContextVar.set() method.They can be passed to the ContextVar.reset() method to revertthe value of the variable to what it was before the correspondingset.

    • Token.var
    • A read-only property. Points to the ContextVar objectthat created the token.

    • 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 to Token.MISSING is the variable was not setbefore the call.

    • Token.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:

  1. ctx: Context = copy_context()
  2. print(list(ctx.items()))

The function has an O(1) complexity, i.e. works equally fast forcontexts with a few context variables and for contexts that havea lot of them.

  • class contextvars.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.

Context implements the collections.abc.Mapping interface.

  • run(callable, *args, **kwargs)
  • Execute callable(args, *kwargs) code in the context objectthe run method is called on. Return the result of the executionor propagate an exception if one occurred.

Any changes to any context variables that callable makes willbe contained in the context object:

  1. var = ContextVar('var')
  2. var.set('spam')
  3.  
  4. def main():
  5. # 'var' was set to 'spam' before
  6. # calling 'copy_context()' and 'ctx.run(main)', so:
  7. # var.get() == ctx[var] == 'spam'
  8.  
  9. var.set('ham')
  10.  
  11. # Now, after setting 'var' to 'ham':
  12. # var.get() == ctx[var] == 'ham'
  13.  
  14. ctx = copy_context()
  15.  
  16. # Any changes that the 'main' function makes to 'var'
  17. # will be contained in 'ctx'.
  18. ctx.run(main)
  19.  
  20. # The 'main()' function was run in the 'ctx' context,
  21. # so changes to 'var' are contained in it:
  22. # ctx[var] == 'ham'
  23.  
  24. # However, outside of 'ctx', 'var' is still set to 'spam':
  25. # var.get() == 'spam'

The method raises a RuntimeError when called on the samecontext object from more than one OS thread, or when calledrecursively.

  • copy()
  • Return a shallow copy of the context object.

  • var in context

  • Return True if the context has a value for var set;return False otherwise.

  • context[var]

  • Return the value of the varContextVar variable.If the variable is not set in the context object, aKeyError is raised.

  • get(var[, default])

  • Return the value for var if var has the value in the contextobject. Return default otherwise. If default 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 support

Context variables are natively supported in asyncio 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:

  1. import asyncio
  2. import contextvars
  3.  
  4. client_addr_var = contextvars.ContextVar('client_addr')
  5.  
  6. def render_goodbye():
  7. # The address of the currently handled client can be accessed
  8. # without passing it explicitly to this function.
  9.  
  10. client_addr = client_addr_var.get()
  11. return f'Good bye, client @ {client_addr}\n'.encode()
  12.  
  13. async def handle_request(reader, writer):
  14. addr = writer.transport.get_extra_info('socket').getpeername()
  15. client_addr_var.set(addr)
  16.  
  17. # In any code that we call is now possible to get
  18. # client's address by calling 'client_addr_var.get()'.
  19.  
  20. while True:
  21. line = await reader.readline()
  22. print(line)
  23. if not line.strip():
  24. break
  25. writer.write(line)
  26.  
  27. writer.write(render_goodbye())
  28. writer.close()
  29.  
  30. async def main():
  31. srv = await asyncio.start_server(
  32. handle_request, '127.0.0.1', 8081)
  33.  
  34. async with srv:
  35. await srv.serve_forever()
  36.  
  37. asyncio.run(main())
  38.  
  39. # To test it you can use telnet:
  40. # telnet 127.0.0.1 8081