Last active
March 17, 2017 18:43
-
-
Save adonig/60e2ad54683996ca5faf219d27140439 to your computer and use it in GitHub Desktop.
What happens in context, stays in context.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from contextlib import AbstractContextManager | |
from types import SimpleNamespace | |
class Context(SimpleNamespace, AbstractContextManager): | |
def __enter__(self): | |
self._globals = dict(globals()) | |
globals().update(self.__dict__) | |
return self | |
def __exit__(self, *exc): | |
for key, val in globals().items(): | |
if key in self.__dict__: | |
self.__dict__[key] = val | |
globals().clear() | |
globals().update(self._globals) | |
return False | |
a = 1 | |
b = 1 | |
ctx = Context(a=2, b=2, c=42) | |
assert a == 1 | |
assert b == 1 | |
with ctx: | |
assert a == 2 | |
assert b == 2 | |
assert c == 42 | |
a += b | |
assert a == 4 | |
assert a == 1 | |
assert b == 1 | |
assert 'c' not in globals() | |
with ctx: | |
assert a == 4 | |
assert b == 2 | |
assert c == 42 | |
# Using Context like a "let" expression | |
with Context(a=1, b=2): | |
a += b | |
assert a == 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment