Created
January 15, 2019 16:41
-
-
Save GammaGames/10d1c2b5d8a01a591bcd77014571e4f3 to your computer and use it in GitHub Desktop.
Javascript-like "let" variables. From https://nvbn.github.io/2014/09/25/let-statement-in-python/
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 | |
from inspect import currentframe, getouterframes | |
@contextmanager | |
def let(**bindings): | |
frame = getouterframes(currentframe(), 2)[-1][0] # 2 because first frame in `contextmanager` decorator | |
locals_ = frame.f_locals | |
original = {var: locals_.get(var) for var in bindings.keys()} | |
locals_.update(bindings) | |
yield | |
locals_.update(original) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment