Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Context Variables
Context variables can have different values depending on their context. Unlike Thread-Local Storage where each execution thread may have a different value for a variable, a context variable may have several contexts in one execution thread. This is useful for keeping track of variables in concurrent asynchronous tasks.
The ContextVar class is used to declare and work with Context Variables.
Creating a Context Variable
You can create a context variable with an optional default value ?
import contextvars
name = contextvars.ContextVar("name", default="Hello")
print(f"Variable name: {name.name}")
print(f"Default value: {name.get()}")
Variable name: name Default value: Hello
The optional default parameter is returned by ContextVar.get() when no value for the variable is found in the current context.
ContextVar Methods
Using get() and set()
The get() method retrieves the current value, while set() assigns a new value ?
import contextvars
name = contextvars.ContextVar("name", default="World")
# Get current value
print(f"Initial: {name.get()}")
# Set a new value
token = name.set("Python")
print(f"After set: {name.get()}")
Initial: World After set: Python
Using reset()
The reset() method restores the previous value using a token ?
import contextvars
name = contextvars.ContextVar("name", default="World")
print(f"Original: {name.get()}")
token = name.set("Python")
print(f"After set: {name.get()}")
# Reset to previous value
name.reset(token)
print(f"After reset: {name.get()}")
Original: World After set: Python After reset: World
Working with Context Objects
The Context class is a mapping of Context Variables to their values. You can create contexts and run code within them ?
import contextvars
name = contextvars.ContextVar("name")
age = contextvars.ContextVar("age")
# Set values in current context
name.set("Alice")
age.set(25)
# Create a new context
ctx = contextvars.Context()
print(f"Empty context length: {len(ctx)}")
# Copy current context
current_ctx = contextvars.copy_context()
print(f"Current context length: {len(current_ctx)}")
print(f"Variables: {list(current_ctx.keys())}")
Empty context length: 0 Current context length: 2 Variables: [<ContextVar name='name' at 0x...>, <ContextVar name='age' at 0x...>]
Running Code in Different Contexts
You can execute functions within specific contexts using the run() method ?
import contextvars
name = contextvars.ContextVar("name", default="Unknown")
def print_name():
return f"Name: {name.get()}"
# Set value in current context
name.set("Alice")
print("Current context:", print_name())
# Create new context and run function
new_ctx = contextvars.Context()
result = new_ctx.run(print_name)
print("New context:", result)
# Original context unchanged
print("Back to current:", print_name())
Current context: Name: Alice New context: Name: Unknown Back to current: Name: Alice
Context Variable Methods Summary
| Method | Description |
|---|---|
get(default=None) |
Return current value or default if not set |
set(value) |
Set new value, returns token for reset |
reset(token) |
Reset to value before set() that created token |
Context Object Methods Summary
| Method | Description |
|---|---|
copy() |
Returns shallow copy of context |
run(callable, *args, **kwargs) |
Execute callable in this context |
get(var, default=None) |
Get value for context variable |
keys() |
Returns all variables in context |
values() |
Returns all variable values |
items() |
Returns (variable, value) pairs |
Conclusion
Context variables provide isolated storage for values across different execution contexts. Use ContextVar for declaring variables and Context objects for managing execution environments in asynchronous applications.
