On this page
threading.local
Prev: threading.gettrace | Up: threading | Next: threading.Lock
Rel: threading.active_count, threading.Barrier, threading.BoundedSemaphore, threading.BrokenBarrierError
Ref: docs.python.org — threading.local
Tags: #public #python3 #stdlib #threading
Import
import threading
from threading import local
Signature & Overview
threading.local()
Thread-local data
Usage
import threading
tls = threading.local()
tls.user = "main"
seen: list[str] = []
def worker() -> None:
tls.user = "worker"
seen.append(tls.user)
t = threading.Thread(target=worker)
t.start()
t.join()
assert tls.user == "main" and seen == ["worker"]
Gotchas
- Thread-isolated attributes, NOT async-task isolated: In
asynciocoroutines running on one thread,threading.local()is shared across tasks—usecontextvars.ContextVarfor async code.
REPL Inspect
from threading import local
help(local)
Linked from
Related notes
- tuts/python3/stdlib_module/threading/gettrace Linked here; links to this page; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/Lock Linked here; links to this page; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/threading/active_count Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/Barrier Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/BoundedSemaphore Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/BrokenBarrierError Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/Condition shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/current_thread shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/enumerate shared tags: #stdlib, #threading