Last active
August 29, 2015 14:21
-
-
Save mathershifter/b8ec377e1387de8a03b1 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
import collections | |
class ResolvingDict(collections.MutableMapping): | |
"""Find a key in current or parent node""" | |
def __init__(self, mapping, parent=None): | |
self.store = dict() | |
self.update(mapping) | |
self.parent = parent | |
def __setitem__(self, key, value): | |
self.store[key] = value | |
def __getitem__(self, item): | |
if self.parent and item not in self.store: | |
value = self.parent[item] | |
else: | |
value = self.store[item] | |
if hasattr(value, "__iter__"): | |
return ResolvingDict(value, parent=self) | |
else: | |
return value | |
def __delitem__(self, key): | |
del(self.store[key]) | |
def __iter__(self): | |
return iter(self.store) | |
def __len__(self): | |
return len(self.store) | |
def __repr__(self): | |
return str(self.store) | |
if __name__ == "__main__": | |
d = { | |
"key1": "value1", | |
"key2": "value2", | |
"node1": { | |
"key1": "value1.1" | |
} | |
} | |
d = ResolvingDict(d) | |
print d["node1"]["key2"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment