Skip to content

Instantly share code, notes, and snippets.

@defnull
Created April 30, 2010 19:15
Show Gist options
  • Save defnull/385629 to your computer and use it in GitHub Desktop.
Save defnull/385629 to your computer and use it in GitHub Desktop.
class ContextLocal(object):
__slots__ = ('_local_init_args', '_local_contexts', '_local_context_ident')
def __new__(cls, *args, **kwargs):
self = object.__new__(cls)
object.__setattr__(self, '_local_init_args', (args, kwargs))
object.__setattr__(self, '_local_contexts', {})
object.__setattr__(self, '_local_context_ident', lambda: 0)
return self
def set_context_ident(self, func):
object.__setattr__(self, '_local_context_ident', func)
def _get_local(self):
cur = self._local_context_ident()
context = self._local_contexts.get(cur)
if not context:
self._local_contexts[cur] = context = {}
args, kwargs = self._local_init_args
self.__init__(*args, **kwargs)
return context
def __getattr__(self, attr):
try:
return self._get_local()[attr]
except KeyError:
raise AttributeError(attr)
def __setattr__(self, attr, value):
self._get_local()[attr] = value
def __delattr__(self, attr):
try:
del self._get_local()[attr]
except KeyError:
raise AttributeError(attr)
# threading.local example
import thread
class ThreadLocal(ContextLocal):
def _local_context_ident(self):
thread.getCurrentThread()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment