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_context2 # Create context variable with type hint and default3request_id: ContextVar[str] = ContextVar("request_id", default="none")4 # Function that accesses the context variable5def process_request(): # Get current value from context6 print(f"Processing request: {request_id.get()}")7 # Handler that sets context for a request8def handle_request(rid): # Set new value and get token for reset9 token = request_id.set(rid) # Try block ensures cleanup happens10 try: # Process with new context value11 process_request() # Finally ensures reset even if error occurs12 finally: # Reset to previous value using token13 request_id.reset(token)14 # Handle first request15handle_request("req-123")# Handle second request16handle_request("req-456")# Verify context is reset to default17print(f"After: {request_id.get()}")Output
Processing request: req-123 Processing request: req-456 After: none
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