Created
November 20, 2013 07:21
-
-
Save Mause/7559046 to your computer and use it in GitHub Desktop.
A simple inheriting dictionary implementation written in Python, with some inspiration taken from EmberJS' internals.
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
import collections | |
class InheritDict(collections.UserDict): | |
def __init__(self, data, parent=None): | |
for k, v in data.items(): | |
if isinstance(data[k], dict): | |
data[k] = InheritDict(data[k], self) | |
super().__init__(data) | |
self.parent = parent | |
def __getitem__(self, key): | |
try: | |
return self.data[key] | |
except KeyError: | |
if self.parent: | |
return self.parent[key] | |
else: | |
raise | |
data = { | |
'repository': 'url', | |
'web': { | |
'conf': 'lol', | |
'google': { | |
'conf': 'overwrites lol' | |
}, | |
'bing': {} | |
} | |
} | |
d = InheritDict(data) | |
assert d['repository'] == 'url' | |
assert d['web']['conf'] == 'lol' | |
assert d['web']['google']['conf'] == 'overwrites lol' | |
assert d['web']['bing']['conf'] == 'lol' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment