1 # This is a backport of Python-2.4's threading.local() implementation
3 """Thread-local objects
5 (Note that this module provides a Python version of thread
6 threading.local class. Depending on the version of Python you're
7 using, there may be a faster one available. You should always import
8 the local class from threading.)
10 Thread-local objects support the management of thread-local data.
11 If you have data that you want to be local to a thread, simply create
12 a thread-local object and use its attributes:
15 >>> mydata.number = 42
19 You can also access the local-object's dictionary:
23 >>> mydata.__dict__.setdefault('widgets', [])
28 What's important about thread-local objects is that their data are
29 local to a thread. If we access the data in a different thread:
33 ... items = mydata.__dict__.items()
36 ... mydata.number = 11
37 ... log.append(mydata.number)
40 >>> thread = threading.Thread(target=f)
46 we get different data. Furthermore, changes made in the other thread
47 don't affect data seen in this thread:
52 Of course, values you get from a local object, including a __dict__
53 attribute, are for whatever thread was current at the time the
54 attribute was read. For that reason, you generally don't want to save
55 these values across threads, as they apply only to the thread they
58 You can create custom local objects by subclassing the local class:
60 >>> class MyLocal(local):
62 ... initialized = False
63 ... def __init__(self, **kw):
64 ... if self.initialized:
65 ... raise SystemError('__init__ called too many times')
66 ... self.initialized = True
67 ... self.__dict__.update(kw)
68 ... def squared(self):
69 ... return self.number ** 2
71 This can be useful to support default values, methods and
72 initialization. Note that if you define an __init__ method, it will be
73 called each time the local object is used in a separate thread. This
74 is necessary to initialize each thread's dictionary.
76 Now if we create a local object:
78 >>> mydata = MyLocal(color='red')
80 Now we have a default number:
91 And a method that operates on the data:
96 As before, we can access the data in a separate thread:
99 >>> thread = threading.Thread(target=f)
103 [[('color', 'red'), ('initialized', True)], 11]
105 without affecting this thread's data:
110 Traceback (most recent call last):
112 AttributeError: 'MyLocal' object has no attribute 'color'
114 Note that subclasses can define slots, but they are not thread
115 local. They are shared across threads:
117 >>> class MyLocal(local):
118 ... __slots__ = 'number'
120 >>> mydata = MyLocal()
121 >>> mydata.number = 42
122 >>> mydata.color = 'red'
124 So, the separate thread:
126 >>> thread = threading.Thread(target=f)
138 # Threading import is at end
140 class _localbase(object):
141 __slots__
= '_local__key', '_local__args', '_local__lock'
143 def __new__(cls
, *args
, **kw
):
144 self
= object.__new
__(cls
)
145 key
= 'thread.local.' + str(id(self
))
146 object.__setattr
__(self
, '_local__key', key
)
147 object.__setattr
__(self
, '_local__args', (args
, kw
))
148 object.__setattr
__(self
, '_local__lock', RLock())
150 if args
or kw
and (cls
.__init
__ is object.__init
__):
151 raise TypeError("Initialization arguments are not supported")
153 # We need to create the thread dict in anticipation of
154 # __init__ being called, to make sure we don't call it
156 dict = object.__getattribute
__(self
, '__dict__')
157 currentThread().__dict
__[key
] = dict
162 key
= object.__getattribute
__(self
, '_local__key')
163 d
= currentThread().__dict
__.get(key
)
166 currentThread().__dict
__[key
] = d
167 object.__setattr
__(self
, '__dict__', d
)
169 # we have a new instance dict, so call out __init__ if we have
172 if cls
.__init
__ is not object.__init
__:
173 args
, kw
= object.__getattribute
__(self
, '_local__args')
174 cls
.__init
__(self
, *args
, **kw
)
176 object.__setattr
__(self
, '__dict__', d
)
178 class local(_localbase
):
180 def __getattribute__(self
, name
):
181 lock
= object.__getattribute
__(self
, '_local__lock')
185 return object.__getattribute
__(self
, name
)
189 def __setattr__(self
, name
, value
):
190 lock
= object.__getattribute
__(self
, '_local__lock')
194 return object.__setattr
__(self
, name
, value
)
198 def __delattr__(self
, name
):
199 lock
= object.__getattribute
__(self
, '_local__lock')
203 return object.__delattr
__(self
, name
)
209 threading_enumerate
= enumerate
210 __getattribute__
= object.__getattribute
__
213 key
= __getattribute__(self
, '_local__key')
216 threads
= list(threading_enumerate())
218 # if enumerate fails, as it seems to do during
219 # shutdown, we'll skip cleanup under the assumption
220 # that there is nothing to clean up
223 for thread
in threads
:
225 __dict__
= thread
.__dict
__
226 except AttributeError:
227 # Thread is dying, rest in peace
234 pass # didn't have anything in this thread
239 from threading
import currentThread
, enumerate, RLock