import threading
import weakref

__all__ = ['local']

class _local(object):
    """
    Crappy Python 2.3 compatible implementation of thread-local storage
    """

    __slots__ = ('__thread_dict__',)

    def __init__(self):
        object.__setattr__(self, '__thread_dict__', weakref.WeakKeyDictionary())
        
    def __getattr__(self, attr):
        try:
            return self.__thread_dict__[threading.currentThread()][attr]
        except KeyError:
            raise AttributeError(attr)

    def __setattr__(self, attr, value):
        t = threading.currentThread()
        try:
            d = self.__thread_dict__[t]
        except KeyError:
            d = self.__thread_dict__[t] = {}
        d[attr] = value

try:
    local = threading.local
except AttributeError:
    local = _local
