from collections import MutableMapping class Scope(MutableMapping): def __init__(self, parent=None): self._parent = parent self._scope = {} def __getitem__(self, key): if key in self._scope: return self._scope[key] elif self._parent is not None: return self._parent[key] else: raise KeyError(key) def __setitem__(self, key, value): self._scope[key] = value def __delitem__(self, key): del self._scope[key] def __iter__(self): for key in self._scope: yield key if self._parent is not None: for key in iter(self._parent): yield key def __len__(self): return len(self._scope) + len(self._parent) if self._parent else 0 def __repr__(self): return repr(dict(self)) def __getattr__(self, key): return self.__getitem__(key) A = Scope() B = Scope(A) A['hello'] = 'hi there' print A['hello'] print B['hello'] B['hello'] = 'goodbye' print A['hello'] print B['hello'] print A print B print A.hello B.hello = 'good morning' print B
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question