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.

Medium Python 3.9+ Aug 9, 2026 Concurrency & performance 14 views 0 copies

Python code

19 lines
Python 3.9+
import 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

stdout
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

  1. Use a dictionary with the current thread's ident: `storage = {}` then `storage[threading.get_ident()] = value`
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Concurrency & performance

Related tutorials and quizzes for this topic.