Python
Advanced
What is Python Context Variable?
A variable that maintains separate values for each execution context, enabling implicit state passing in async code without global variables.
The contextvars module (Python 3.7+) provides context-local storage similar to thread-local storage but designed for asyncio. ContextVar objects maintain separate values for each async task or thread. This is essential for passing request-specific data (request ID, user context, database session) through async call chains without explicitly threading parameters through every function. Framework use cases include logging correlation IDs, database transaction scoping, and request-local caching. Unlike global variables, context variables are isolated per execution context. The copy_context() function creates snapshots for running code with specific context values.