Skip to content

Instantly share code, notes, and snippets.

@Mause
Created November 20, 2013 07:21
Show Gist options
  • Save Mause/7559046 to your computer and use it in GitHub Desktop.
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.
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