3 from __future__
import absolute_import
4 from __future__
import division
5 from __future__
import print_function
6 from __future__
import unicode_literals
12 def __init__(self, cls, allow_default, arg_name):
24 def enter(self, value):
27 def exit(self, value):
28 assert len(self.
_stack) > 0,
'Context %s is empty.' % self.
cls 29 assert self.
_stack.pop() == value
31 def get_active(self, required=True):
36 'Context %s is required but none is active.' % self.
cls)
45 def register(self, ctx_info):
46 assert isinstance(ctx_info, ContextInfo)
47 assert (ctx_info.cls
not in self.
_ctxs), (
48 'Context %s already registered' % ctx_info.cls)
49 self.
_ctxs[ctx_info.cls] = ctx_info
52 assert cls
in self.
_ctxs,
'Context %s not registered.' % cls
53 return self.
_ctxs[cls]
59 def context_manager():
60 global _CONTEXT_MANAGER
61 return _CONTEXT_MANAGER
65 if self._prev_enter
is not None:
67 context_manager().get(self._ctx_class).enter(self)
71 def __exit__(self, *args):
72 context_manager().get(self._ctx_class).exit(self)
73 if self._prev_exit
is not None:
74 self._prev_exit(*args)
78 def current(cls, value=None, required=True):
79 return get_active_context(cls, value, required)
83 def __init__(self, arg_name=None, allow_default=False):
87 def __call__(self, cls):
88 assert not hasattr(cls,
'_ctx_class'), (
89 '%s parent class (%s) already defines context.' % (
91 context_manager().register(
102 def get_active_context(cls, val=None, required=True):
103 ctx_info = context_manager().get(cls)
105 assert isinstance(val, cls), (
106 'Wrong context type. Expected: %s, got %s.' % (cls, type(val)))
108 return ctx_info.get_active(required=required)