Last active
July 14, 2018 21:58
-
-
Save vindex10/b41392691c8f68f614b63bb6a11eac88 to your computer and use it in GitHub Desktop.
Scoping for 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
class Scope: | |
""" Implementation of scoping. Use it with `with` statement: | |
``` | |
with Scope() as s: | |
s.var = 10 | |
print(s.var) | |
``` | |
""" | |
def __init__(self): | |
self._ = dict() | |
def __enter__(self): | |
return self | |
def __getattr__(self, key): | |
if key != "_": | |
return self._[key] | |
else: | |
super(Scope, self).__getattr__(key) | |
def __setattr__(self, key, val): | |
if key != "_": | |
self._.update({key: val}) | |
else: | |
super(Scope, self).__setattr__(key, val) | |
def __exit__(self, type, value, traceback): | |
self._ = dict() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment