Typing Stubs for contextvars
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
-
Module 'types_contextvars' has no attribute 'ContextVar'
cause The user is attempting to import symbols directly from the `types_contextvars` package, which is incorrect. `types_contextvars` is a stub package for static type checking, not a runtime module.fixImport symbols like `ContextVar` from the standard library `contextvars` module: `from contextvars import ContextVar`. -
Missing type annotations for 'contextvars' (reportMissingTypeStubs)
cause A type checker (like MyPy or Pylance) is reporting that it cannot find type stubs for the `contextvars` module, meaning it cannot properly type-check code using `contextvars`.fixInstall the `types-contextvars` package: `pip install types-contextvars`. Ensure your type checker is configured to use installed stub packages. -
mypy: error: Incompatible default for argument "default" (item is "None", expected "str")
cause This specific MyPy error (or similar) occurs when a `ContextVar` is defined with a type hint that doesn't match the default value, and `types-contextvars` is correctly enforcing the type.fixEnsure the default value provided to `ContextVar` matches the type annotation, or make the type annotation optional (e.g., `ContextVar[Optional[str]]`) if `None` is an expected default and `from typing import Optional` is used.
Warnings
- gotcha Do not attempt to import symbols directly from `types_contextvars` (e.g., `from types_contextvars import ContextVar`). This package only provides type stubs for static analysis, not runtime objects.
- gotcha While typeshed strives for accuracy, stubs might occasionally lag behind the absolute bleeding edge of Python's standard library, especially when using pre-release Python versions or new, undocumented features.
Install
-
pip install types-contextvars
Imports
- ContextVar
from types_contextvars import ContextVar
from contextvars import ContextVar
- copy_context
from types_contextvars import copy_context
from contextvars import copy_context
- Token
from types_contextvars import Token
from contextvars import Token
Quickstart
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()