Last active
August 29, 2015 14:26
-
-
Save crowsonkb/5a4593a3006e7e3924a6 to your computer and use it in GitHub Desktop.
A horrible context manager...
This file contains 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 contextmanager | |
import sys | |
@contextmanager | |
def let(**kwargs): | |
to_del = [] | |
to_set = {} | |
bindings = sys._getframe(2).f_locals | |
for k, v in kwargs.items(): | |
if k in bindings: | |
to_set[k] = bindings[k] | |
else: | |
to_del.append(k) | |
bindings[k] = v | |
yield | |
bindings.update(to_set) | |
for k in to_del: | |
del bindings[k] | |
return False | |
a = 100 | |
with let(a=1, b=2): | |
print(a, b) | |
try: | |
print(a) | |
print(b) | |
except NameError as e: | |
print(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment