Skip to content

Instantly share code, notes, and snippets.

@GammaGames
Created January 15, 2019 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GammaGames/10d1c2b5d8a01a591bcd77014571e4f3 to your computer and use it in GitHub Desktop.
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/
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