author | om |
Mon, 02 Dec 2013 14:02:05 +0100 | |
changeset 3 | 65432e6c6042 |
permissions | -rwxr-xr-x |
om@3 | 1 |
"""Python 2.3 compatabilty""" |
om@3 | 2 |
import threading |
om@3 | 3 |
|
om@3 | 4 |
class threadlocal(object): |
om@3 | 5 |
"""Implementation of threading.local for python2.3. |
om@3 | 6 |
""" |
om@3 | 7 |
def __getattribute__(self, name): |
om@3 | 8 |
if name == "__dict__": |
om@3 | 9 |
return threadlocal._getd(self) |
om@3 | 10 |
else: |
om@3 | 11 |
try: |
om@3 | 12 |
return object.__getattribute__(self, name) |
om@3 | 13 |
except AttributeError: |
om@3 | 14 |
try: |
om@3 | 15 |
return self.__dict__[name] |
om@3 | 16 |
except KeyError: |
om@3 | 17 |
raise AttributeError, name |
om@3 | 18 |
|
om@3 | 19 |
def __setattr__(self, name, value): |
om@3 | 20 |
self.__dict__[name] = value |
om@3 | 21 |
|
om@3 | 22 |
def __delattr__(self, name): |
om@3 | 23 |
try: |
om@3 | 24 |
del self.__dict__[name] |
om@3 | 25 |
except KeyError: |
om@3 | 26 |
raise AttributeError, name |
om@3 | 27 |
|
om@3 | 28 |
def _getd(self): |
om@3 | 29 |
t = threading.currentThread() |
om@3 | 30 |
if not hasattr(t, '_d'): |
om@3 | 31 |
# using __dict__ of thread as thread local storage |
om@3 | 32 |
t._d = {} |
om@3 | 33 |
|
om@3 | 34 |
_id = id(self) |
om@3 | 35 |
# there could be multiple instances of threadlocal. |
om@3 | 36 |
# use id(self) as key |
om@3 | 37 |
if _id not in t._d: |
om@3 | 38 |
t._d[_id] = {} |
om@3 | 39 |
return t._d[_id] |
om@3 | 40 |
|
om@3 | 41 |
if __name__ == '__main__': |
om@3 | 42 |
d = threadlocal() |
om@3 | 43 |
d.x = 1 |
om@3 | 44 |
print d.__dict__ |
om@3 | 45 |
print d.x |
om@3 | 46 |