Thread-local storage keeps a separate copy of a variable for every thread. AlexBerUtils provides three helpers that sit on top of Python’sDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/alex-ber/AlexBerUtils/llms.txt
Use this file to discover all available pages before exploring further.
threading.local() to make this pattern explicit and safe.
Functions
threadlocal_var
Retrieves a thread-local variable by name, creating it with the given factory if it does not yet exist for the current thread.
The
threading.local instance that holds per-thread state.The attribute name to look up (or create) on
thread_locals.A zero-argument callable used to produce the initial value when the variable does not exist for the current thread. Any extra positional or keyword arguments passed after
factory are forwarded to it.get_threadlocal_var
Retrieves a thread-local variable that must already be initialised. Raises ValueError if the variable is None or was never set.
The
threading.local instance.The attribute name to retrieve. A
ValueError is raised if the value is None.del_threadlocal_var
Deletes a thread-local variable silently. Unlike delattr, it does not raise if the variable does not exist.
The
threading.local instance.The attribute name to delete. No error is raised if the attribute does not exist.
Common pattern
The three functions are typically used together to manage the full lifecycle of a per-thread resource:Each thread gets its own independent copy of
db. Changes in one thread never affect another.