1# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) 2# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php 3""" 4Implementation of thread-local storage, for Python versions that don't 5have thread local storage natively. 6""" 7 8try: 9 import threading 10except ImportError: 11 # No threads, so "thread local" means process-global 12 class local(object): 13 pass 14else: 15 try: 16 local = threading.local 17 except AttributeError: 18 # Added in 2.4, but now we'll have to define it ourselves 19 import thread 20 class local(object): 21 22 def __init__(self): 23 self.__dict__['__objs'] = {} 24 25 def __getattr__(self, attr, g=thread.get_ident): 26 try: 27 return self.__dict__['__objs'][g()][attr] 28 except KeyError: 29 raise AttributeError( 30 "No variable %s defined for the thread %s" 31 % (attr, g())) 32 33 def __setattr__(self, attr, value, g=thread.get_ident): 34 self.__dict__['__objs'].setdefault(g(), {})[attr] = value 35 36 def __delattr__(self, attr, g=thread.get_ident): 37 try: 38 del self.__dict__['__objs'][g()][attr] 39 except KeyError: 40 raise AttributeError( 41 "No variable %s defined for thread %s" 42 % (attr, g())) 43 44