Why are contextvars better than threading.local in async Python?

This tests whether you know async tasks share OS threads, making thread-local storage unsafe for request state. A great answer notes ContextVar is task-local and resets automatically, while threading.local bleeds across concurrent coroutines.
This tests whether you understand that async concurrency multiplexes many tasks onto few OS threads, making thread-local storage the wrong granularity and leaking request state between tasks. A great answer covers four points in order: first, threading.local binds to the OS thread, so two concurrent FastAPI requests on the same event-loop thread overwrite each other; second, ContextVar provides context-local state that follows the logical call chain; third, asyncio copies the context into new Tasks so variables like a request ID propagate…
Read the original → docs.python.org
- #python
- #asyncio
- #contextvars
- #fastapi
- #concurrency
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.