fork download
  1. from contextlib import contextmanager
  2. from inspect import currentframe, getouterframes
  3.  
  4. @contextmanager
  5. def let(**bindings):
  6. frame = getouterframes(currentframe(), 2)[-1][0] # 2 because first frame in `contextmanager` is the decorator
  7. locals_ = frame.f_locals
  8. original = {var: locals_.get(var) for var in bindings.keys()}
  9. locals_.update(bindings)
  10. yield
  11. locals_.update(original)
  12.  
  13. def f():
  14. x = 1
  15. with let(x=3):
  16. print(x)
  17.  
  18. f()
  19.  
  20. print(x)
Success #stdin #stdout 0.03s 10244KB
stdin
Standard input is empty
stdout
1
None