1 import threading, weakref
3 __all__ = ["environment", "root", "get", "binding", "var"]
6 __slots__ = ["env", "prev"]
7 def __init__(self, env, prev):
11 class environment(object):
12 __slots__ = ["parent", "map"]
13 def __init__(self, parent=None):
15 self.map = weakref.WeakKeyDictionary()
20 if self.parent is None:
22 return self.parent.get(var)
24 def set(self, var, val):
29 context.prev = stack(cur, context.prev)
33 def __exit__(self, *excinfo):
36 raise Exception("Unbalanced __enter__/__exit__")
37 context.env = prev.env
38 context.prev = prev.prev
43 class context(threading.local):
51 class binding(object):
52 __slots__ = ["bindings"]
53 def __init__(self, bindings):
54 if isinstance(bindings, dict):
55 bindings = bindings.items()
56 self.bindings = bindings
60 new = environment(cur)
61 for var, val in self.bindings:
63 context.prev = stack(cur, context.prev)
67 def __exit__(self, *excinfo):
70 raise Exception("Unbalanced __enter__/__exit__")
71 context.env = prev.env
72 context.prev = prev.prev
76 __slots__ = ["__weakref__"]
77 def __init__(self, default=None):
78 if default is not None:
79 root.map[self] = default
83 return context.env.get(self)
85 def binding(self, val):
86 return binding([(self, val)])