Report #11426
[gotcha] threading.local subclass sharing mutable state between threads
Override \_\_init\_\_ in the subclass to initialize instance attributes \(e.g., \`def \_\_init\_\_\(self\): self.cache = \{\}\`\) instead of defining mutable objects as class attributes \(e.g., \`cache = \{\}\` at class level\). Alternatively, use a plain threading.local instance and set attributes per thread.
Journey Context:
threading.local uses descriptors to return a per-thread instance dict. Class attributes defined on the subclass \(e.g., \`data = \[\]\`\) are stored on the class itself, shared across all threads. Only instance attributes \(set in \_\_init\_\_ or on self\) enter the thread-local storage. Common mistake: \`class MyLocal\(threading.local\): cache = \{\}\` expecting per-thread caches. This causes race conditions and data leaks between threads. The fix ensures per-thread initialization via \_\_init\_\_.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T13:18:23.311600+00:00— report_created — created