Context Variable in Python

Level 5392 keystrokes

This uses ContextVar for thread-safe context management, useful for request-scoped data in async applications.

Python code

# Import ContextVar (copy_context is imported but not used here)
1from contextvars import ContextVar, copy_context
2
# Create context variable with type hint and default
3request_id: ContextVar[str] = ContextVar("request_id", default="none")
4
# Function that accesses the context variable
5def process_request():
# Get current value from context
6 print(f"Processing request: {request_id.get()}")
7
# Handler that sets context for a request
8def handle_request(rid):
# Set new value and get token for reset
9 token = request_id.set(rid)
# Try block ensures cleanup happens
10 try:
# Process with new context value
11 process_request()
# Finally ensures reset even if error occurs
12 finally:
# Reset to previous value using token
13 request_id.reset(token)
14
# Handle first request
15handle_request("req-123")
# Handle second request
16handle_request("req-456")
# Verify context is reset to default
17print(f"After: {request_id.get()}")

Output

Processing request: req-123
Processing request: req-456
After: none
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • _× 12
  • "× 12
  • (× 12
  • )× 12
  • :× 7
  • .× 4
  • =× 3
  • -× 2
  • ,× 2
  • {× 2

More Python examples at level 5

← Python typing practice