← All notes

contextvars stores context-local state for async tasks

Answer: The contextvars module provides APIs to manage, store, and access context-local state. Declare a variable with ContextVar. Use copy_context and Context in asynchronous frameworks. Context managers that have state should use context variables instead of threading.local so that state does not leak across concurrent work. Context Variables should be created at the top module level, and never in closures.

PEP 567 introduced the module for Python 3.7. It is similar to thread-local storage, but it also keeps values per asynchronous task such as asyncio.Task.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, contextvars — Context Variables, PSF-2.0 (https://raw.githubusercontent.com/python/cpython/main/LICENSE); Python PEPs, PEP 567 – Context Variables, Public domain or CC0-1.0 (https://peps.python.org/pep-0567/ (Copyright section: public domain)). Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, contextvars — Context Variables, PSF-2.0 (https://raw.githubusercontent.com/python/cpython/main/LICENSE); Python PEPs, PEP 567 – Context Variables, Public domain or CC0-1.0 (https://peps.python.org/pep-0567/ (Copyright section: public domain)).

Cite this

Permanent ID: iil:note:mtz8hrpa

iinventedlight. 2026. "contextvars stores context-local state for async tasks." iinventedlight Library, iil:note:mtz8hrpa, version of 2026-11-16. https://iinventedlight.com/library/notes/python-contextvars/. License: CC-BY-4.0.

@misc{iil_note_mtz8hrpa,
  author = {{iinventedlight}},
  title = {{contextvars stores context-local state for async tasks}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-16},
  url = {https://iinventedlight.com/library/notes/python-contextvars/},
  note = {Permanent ID iil:note:mtz8hrpa. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-contextvars.md.