all Python 3threadingterm
threading.local
threads
Storage whose attributes are separate for every thread: what one thread writes the others do not see. For example, one database connection per thread.
Syntax
data = threading.local()
data.attr = value # видно только в этом потоке
An attribute assigned in the main thread is simply missing in the others — AttributeError, not a shared value. To give every thread a starting value, subclass threading.local and set it in __init__: it runs again in each thread on first access. Create the object once and share it between threads rather than making it inside a function. In a thread pool the data outlives a task — the next task on the same thread sees it. For asyncio use contextvars: all its coroutines live in one thread.
Examples
import threading
data = threading.local()
data.name = 'main'
seen = []
def worker():
seen.append(hasattr(data, 'name'))
data.name = 'worker'
t = threading.Thread(target=worker)
t.start()
t.join()
print(seen, data.name) # → [False] main
import threading
class Counter(threading.local):
def __init__(self):
self.n = 0
counter = Counter()
results = []
def work(k):
for _ in range(k):
counter.n += 1
results.append(counter.n)
threads = [threading.Thread(target=work, args=(k,)) for k in (1, 2, 3)]
for t in threads:
t.start()
for t in threads:
t.join()
print(sorted(results), counter.n) # → [1, 2, 3] 0
See also
Open in the full glossarydocs.python.orgReport an inaccuracy