3 from __future__
import absolute_import
4 from __future__
import division
5 from __future__
import print_function
6 from __future__
import unicode_literals
13 def __init__(self, cls, allow_default, arg_name):
22 self._local_stack.obj = []
23 return self._local_stack.obj
25 def enter(self, value):
26 self._stack.append(value)
28 def exit(self, value):
29 assert len(self.
_stack) > 0,
'Context %s is empty.' % self.
cls 30 assert self._stack.pop() == value
32 def get_active(self, required=True):
37 'Context %s is required but none is active.' % self.
cls)
46 def register(self, ctx_info):
47 assert isinstance(ctx_info, _ContextInfo)
48 assert (ctx_info.cls
not in self.
_ctxs), (
49 'Context %s already registered' % ctx_info.cls)
50 self.
_ctxs[ctx_info.cls] = ctx_info
53 assert cls
in self.
_ctxs,
'Context %s not registered.' % cls
54 return self.
_ctxs[cls]
60 def _context_registry():
61 global _CONTEXT_REGISTRY
62 return _CONTEXT_REGISTRY
66 if self._prev_enter
is not None:
68 _context_registry().get(self._ctx_class).enter(self)
72 def __exit__(self, *args):
73 _context_registry().get(self._ctx_class).exit(self)
74 if self._prev_exit
is not None:
75 self._prev_exit(*args)
78 def __call__(self, func):
80 def wrapper(*args, **kwargs):
82 return func(*args, **kwargs)
87 def _current(cls, value=None, required=True):
88 return _get_active_context(cls, value, required)
92 def __init__(self, arg_name=None, allow_default=False):
96 def __call__(self, cls):
97 assert not hasattr(cls,
'_ctx_class'), (
98 '%s parent class (%s) already defines context.' % (
102 _context_registry().register(
117 def _get_active_context(cls, val=None, required=True):
118 ctx_info = _context_registry().get(cls)
120 assert isinstance(val, cls), (
121 'Wrong context type. Expected: %s, got %s.' % (cls, type(val)))
123 return ctx_info.get_active(required=required)