Typing Stubs for contextvars

2.4.7.3 · active · verified Fri Apr 17

This package provides static type checking definitions (typing stubs) for the built-in Python `contextvars` standard library module. It enables type checkers like MyPy to correctly analyze code that uses `contextvars`, ensuring type safety without altering runtime behavior. The current version is 2.4.7.3, and releases are tied to updates in the Python standard library and the broader typeshed project.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates basic usage of `contextvars` with type annotations. Installing `types-contextvars` allows static type checkers (like MyPy) to validate the types of `my_var`, `ContextVar` methods, and related functions, ensuring your code adheres to type definitions without affecting runtime execution.

import contextvars

# Define a ContextVar with a type hint
my_var: contextvars.ContextVar[str] = contextvars.ContextVar('my_var', default='default_value')

def worker_task():
    print(f"Worker: my_var is {my_var.get()}")

def main():
    print(f"Main: my_var is {my_var.get()}")
    
    # Set a new value for my_var in the current context
    token = my_var.set('new_value_in_main')
    print(f"Main (after set): my_var is {my_var.get()}")
    
    worker_task()
    
    # Restore the previous value
    my_var.reset(token)
    print(f"Main (after reset): my_var is {my_var.get()}")

if __name__ == '__main__':
    # Installing `types-contextvars` (e.g., `pip install types-contextvars`)
    # allows static type checkers (like MyPy) to validate these type annotations.
    # Example: run `mypy your_script.py` after installation.
    main()

view raw JSON →