(Note that this module provides a Python version of the threading.local
class. Depending on the version of Python you're using, there may be a
faster one available. You should always import the `local` class from
Thread-local objects support the management of thread-local data.
If you have data that you want to be local to a thread, simply create
a thread-local object and use its attributes:
You can also access the local-object's dictionary:
>>> mydata.__dict__.setdefault('widgets', [])
What's important about thread-local objects is that their data are
local to a thread. If we access the data in a different thread:
... items = sorted(mydata.__dict__.items())
... log.append(mydata.number)
>>> thread = threading.Thread(target=f)
we get different data. Furthermore, changes made in the other thread
don't affect data seen in this thread:
Of course, values you get from a local object, including a __dict__
attribute, are for whatever thread was current at the time the
attribute was read. For that reason, you generally don't want to save
these values across threads, as they apply only to the thread they
You can create custom local objects by subclassing the local class:
>>> class MyLocal(local):
... def __init__(self, **kw):
... self.__dict__.update(kw)
... return self.number ** 2
This can be useful to support default values, methods and
initialization. Note that if you define an __init__ method, it will be
called each time the local object is used in a separate thread. This
is necessary to initialize each thread's dictionary.
Now if we create a local object:
>>> mydata = MyLocal(color='red')
Now we have a default number:
And a method that operates on the data:
As before, we can access the data in a separate thread:
>>> thread = threading.Thread(target=f)
without affecting this thread's data:
Traceback (most recent call last):
AttributeError: 'MyLocal' object has no attribute 'color'
Note that subclasses can define slots, but they are not thread
local. They are shared across threads:
>>> class MyLocal(local):
>>> thread = threading.Thread(target=f)
from contextlib import contextmanager
# We need to use objects from the threading module, but the threading
# module may also want to use our `local` class, if support for locals
# isn't compiled in to the `thread` module. This creates potential problems
# with circular imports. For that reason, we don't import `threading`
# until the bottom of this file (a hack sufficient to worm around the
# potential problems). Note that all platforms on CPython do have support
# for locals in the `thread` module, and there is no circular import problem
# then, so problems introduced by fiddling the order of imports here won't
"""A class managing thread-local dicts"""
__slots__ = 'key', 'dicts', 'localargs', 'locallock', '__weakref__'
# The key used in the Thread objects' attribute dicts.
# We keep it a string for speed but make it unlikely to clash with
self.key = '_threading_local._localimpl.' + str(id(self))
# { id(Thread) -> (ref(Thread), thread-local dict) }
"""Return the dict for the current thread. Raises KeyError if none
thread = current_thread()
return self.dicts[id(thread)][1]
"""Create a new dict for the current thread, and return it."""
thread = current_thread()
def local_deleted(_, key=key):
# When the localimpl is deleted, remove the thread attribute.
def thread_deleted(_, idt=idt):
# When the thread is deleted, remove the local dict.
# Note that this is suboptimal if the thread object gets
# caught in a reference loop. We would like to be called
# as soon as the OS-level thread ends instead.
dct = local.dicts.pop(idt)
wrlocal = ref(self, local_deleted)
wrthread = ref(thread, thread_deleted)
thread.__dict__[key] = wrlocal
self.dicts[idt] = wrthread, localdict
impl = object.__getattribute__(self, '_local__impl')
args, kw = impl.localargs
self.__init__(*args, **kw)
object.__setattr__(self, '__dict__', dct)
__slots__ = '_local__impl', '__dict__'
def __new__(cls, *args, **kw):
if (args or kw) and (cls.__init__ is object.__init__):
raise TypeError("Initialization arguments are not supported")
self = object.__new__(cls)
impl.localargs = (args, kw)
object.__setattr__(self, '_local__impl', impl)
# We need to create the thread dict in anticipation of
# __init__ being called, to make sure we don't call it
def __getattribute__(self, name):
return object.__getattribute__(self, name)
def __setattr__(self, name, value):
"%r object attribute '__dict__' is read-only"
% self.__class__.__name__)
return object.__setattr__(self, name, value)
def __delattr__(self, name):
"%r object attribute '__dict__' is read-only"
% self.__class__.__name__)
return object.__delattr__(self, name)
from threading import current_thread, RLock