contextvars | Python Standard Library – Real Python

The Python contextvars module supports managing context state, allowing you to store and retrieve data that is local to a context, such as a specific asynchronous task or thread, without interfering with other contexts.

This module is particularly useful in asynchronous programming where different tasks might need to maintain their own separate states.

Here’s a quick example:

Key Features

  • Enables definition of context-local variables
  • Supports asynchronous programming by maintaining separate states for tasks
  • Ensures context management that doesn’t interfere with other contexts
  • Enables deterministic context switching in asynchronous tasks and callback
  • Integrates with tracing and logging by propagating context variables implicitly
  • Supports snapshotting or copying of execution context via copy_context()

Frequently Used Classes and Functions

Examples

Copying and using a context:

Common Use Cases

  • Storing request-specific data in web applications
  • Maintaining task-local data in asynchronous programming
  • Managing state in multithreaded applications without using thread-local storage
  • Storing and retrieving request-scoped data in asynchronous web frameworks
  • Preserving task-local state across coroutines without using globals or passing state explicitly
  • Propagating logging and tracing metadata automatically throughout an execution context
  • Overriding or mocking context state in testing environments in a controlled way
  • Managing context when mixing threads and async tasks to avoid state bleeding

Real-World Example

When you’re handling multiple incoming user requests concurrently. Each request must maintain its own metadata, such as a unique request ID, without interfering with other requests. The contextvars module enables exactly this kind of isolation:

In this example, contextvars allows each request to maintain its own request_id state without interfering with other requests.