Created
September 13, 2015 20:53
-
-
Save boredzo/ae6ce1467a1b0053ff7a to your computer and use it in GitHub Desktop.
Experiment in making a “with” object that injects variables into the subjected scope and removes them at the end. One fatal flaw—see last comment. Inspired by: https://twitter.com/SwedishForSize/status/643146539897090048
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
| class scope(object): | |
| def __init__(self, **kargs): | |
| self.values = kargs | |
| def __enter__(self): | |
| import inspect | |
| frame, filename, lineno, module, code_context, idx = inspect.stack()[1] | |
| caller_args, caller_fargs, caller_kargs, caller_locals = inspect.getargvalues(frame) | |
| dest = caller_kargs if caller_kargs is not None else caller_locals | |
| self.saved = dict(dest) | |
| dest.update(self.values) | |
| def __exit__(self, exc_type, exc_value, traceback): | |
| import inspect | |
| frame, filename, lineno, module, code_context, idx = inspect.stack()[1] | |
| caller_args, caller_fargs, caller_kargs, caller_locals = inspect.getargvalues(frame) | |
| dest = caller_kargs if caller_kargs is not None else caller_locals | |
| for k in self.values: | |
| if k not in self.saved: | |
| del dest[k] | |
| else: | |
| dest[k] = self.saved[k] | |
| def test_func(): | |
| with scope(i="scoped i"): | |
| print i | |
| def test(): | |
| print j | |
| with scope(i="scoped i", j="scoped j"): | |
| print i | |
| test() | |
| try: | |
| print i #should fail | |
| except NameError: | |
| print 'Cleanup succeeded' | |
| #Fails because function scopes are not writable - the changes have no effect | |
| test_func() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment