1
"""Thread-local objects.
3
(Note that this module provides a Python version of the threading.local
4
class. Depending on the version of Python you're using, there may be a
5
faster one available. You should always import the `local` class from
8
Thread-local objects support the management of thread-local data.
9
If you have data that you want to be local to a thread, simply create
10
a thread-local object and use its attributes:
13
>>> mydata.number = 42
17
You can also access the local-object's dictionary:
21
>>> mydata.__dict__.setdefault('widgets', [])
26
What's important about thread-local objects is that their data are
27
local to a thread. If we access the data in a different thread:
31
... items = sorted(mydata.__dict__.items())
33
... mydata.number = 11
34
... log.append(mydata.number)
37
>>> thread = threading.Thread(target=f)
43
we get different data. Furthermore, changes made in the other thread
44
don't affect data seen in this thread:
49
Of course, values you get from a local object, including a __dict__
50
attribute, are for whatever thread was current at the time the
51
attribute was read. For that reason, you generally don't want to save
52
these values across threads, as they apply only to the thread they
55
You can create custom local objects by subclassing the local class:
57
>>> class MyLocal(local):
59
... initialized = False
60
... def __init__(self, **kw):
61
... if self.initialized:
62
... raise SystemError('__init__ called too many times')
63
... self.initialized = True
64
... self.__dict__.update(kw)
65
... def squared(self):
66
... return self.number ** 2
68
This can be useful to support default values, methods and
69
initialization. Note that if you define an __init__ method, it will be
70
called each time the local object is used in a separate thread. This
71
is necessary to initialize each thread's dictionary.
73
Now if we create a local object:
75
>>> mydata = MyLocal(color='red')
77
Now we have a default number:
88
And a method that operates on the data:
93
As before, we can access the data in a separate thread:
96
>>> thread = threading.Thread(target=f)
100
[[('color', 'red'), ('initialized', True)], 11]
102
without affecting this thread's data:
107
Traceback (most recent call last):
109
AttributeError: 'MyLocal' object has no attribute 'color'
111
Note that subclasses can define slots, but they are not thread
112
local. They are shared across threads:
114
>>> class MyLocal(local):
115
... __slots__ = 'number'
117
>>> mydata = MyLocal()
118
>>> mydata.number = 42
119
>>> mydata.color = 'red'
121
So, the separate thread:
123
>>> thread = threading.Thread(target=f)
137
# We need to use objects from the threading module, but the threading
138
# module may also want to use our `local` class, if support for locals
139
# isn't compiled in to the `thread` module. This creates potential problems
140
# with circular imports. For that reason, we don't import `threading`
141
# until the bottom of this file (a hack sufficient to worm around the
142
# potential problems). Note that almost all platforms do have support for
143
# locals in the `thread` module, and there is no circular import problem
144
# then, so problems introduced by fiddling the order of imports here won't
145
# manifest on most boxes.
147
class _localbase(object):
148
__slots__ = '_local__key', '_local__args', '_local__lock'
150
def __new__(cls, *args, **kw):
151
self = object.__new__(cls)
152
key = '_local__key', 'thread.local.' + str(id(self))
153
object.__setattr__(self, '_local__key', key)
154
object.__setattr__(self, '_local__args', (args, kw))
155
object.__setattr__(self, '_local__lock', RLock())
157
if args or kw and (cls.__init__ is object.__init__):
158
raise TypeError("Initialization arguments are not supported")
160
# We need to create the thread dict in anticipation of
161
# __init__ being called, to make sure we don't call it
163
dict = object.__getattribute__(self, '__dict__')
164
current_thread().__dict__[key] = dict
169
key = object.__getattribute__(self, '_local__key')
170
d = current_thread().__dict__.get(key)
173
current_thread().__dict__[key] = d
174
object.__setattr__(self, '__dict__', d)
176
# we have a new instance dict, so call out __init__ if we have
179
if cls.__init__ is not object.__init__:
180
args, kw = object.__getattribute__(self, '_local__args')
181
cls.__init__(self, *args, **kw)
183
object.__setattr__(self, '__dict__', d)
185
class local(_localbase):
187
def __getattribute__(self, name):
188
lock = object.__getattribute__(self, '_local__lock')
192
return object.__getattribute__(self, name)
196
def __setattr__(self, name, value):
197
lock = object.__getattribute__(self, '_local__lock')
201
return object.__setattr__(self, name, value)
205
def __delattr__(self, name):
206
lock = object.__getattribute__(self, '_local__lock')
210
return object.__delattr__(self, name)
217
key = object.__getattribute__(self, '_local__key')
220
threads = list(threading.enumerate())
222
# If enumerate fails, as it seems to do during
223
# shutdown, we'll skip cleanup under the assumption
224
# that there is nothing to clean up.
227
for thread in threads:
229
__dict__ = thread.__dict__
230
except AttributeError:
231
# Thread is dying, rest in peace.
238
pass # didn't have anything in this thread
240
from threading import current_thread, RLock