How to Use threading.local for Per-Thread Data in Python
Use threading.local to keep thread-specific data — each thread gets its own copy of the attribute, so values don't leak between threads.
Python code
19 linesimport threading
import time
local_storage = threading.local()
def worker(name):
local_storage.name = name
time.sleep(0.1)
print(f"Thread {threading.current_thread().name}: {local_storage.name}")
if __name__ == "__main__":
threads = []
for i in range(3):
t = threading.Thread(target=worker, args=(f"Thread-{i}",), name=f"T{i}")
threads.append(t)
t.start()
for t in threads:
t.join()
Output
Thread T0: Thread-0
Thread T1: Thread-1
Thread T2: Thread-2
How it works
threading.local() creates a storage object where attribute assignments like local_storage.name are scoped per thread. Each thread accesses its own copy automatically — no locks needed because the data isn't shared. The time.sleep(0.1) simulates concurrent work so you'd see mismatched values if the storage weren't per-thread.
Common mistakes
- Using a plain dictionary keyed by thread ID instead of threading.local
- Assuming one threading.local instance shares data across threads
- Forgetting to call join() before program exits — main thread may terminate early
Variations
- Use a dictionary with the current thread's ident: `storage = {}` then `storage[threading.get_ident()] = value`
- Subclass threading.local to define default values via __init__
Real-world use cases
- Carrying per-request user IDs in a Flask or Django app's worker threads.
- Storing thread-specific database connections or session objects in an async pool.
- Tracking per-thread metrics like counters or start times in a monitoring tool.
Sponsored
More from Concurrency & performance
- Benchmark list.append vs deque.append in Python medium
- Build a Python Performance Profiler That Generates Readable Reports medium
- Graceful Shutdown Executor Context Manager in Python medium
- How to Build a Producer-Consumer Pattern with asyncio.Queue in Python medium
- How to Cancel an asyncio Task with Graceful Cleanup in Python medium
- How to Convert Data in Parallel with ThreadPoolExecutor in Python easy
Keep learning
Related tutorials and quizzes for this topic.