Created
February 11, 2016 19:46
-
-
Save treystout/f94de50e8a3f56e28afe 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
class AccessorDict(dict): | |
def __getitem__(self, key): | |
"""Handle access like foo['bar'] | |
Wrap any raw dicts in new AccessorDict instances | |
""" | |
out = super(AccessorDict, self).__getitem__(key) | |
if isinstance(out, dict): | |
out = AccessorDict(out) | |
return out | |
def __getattr__(self, attr, default=None): | |
"""Handle access like foo.bar | |
Wrap any raw dicts in new AccessorDict instances | |
""" | |
if attr in self.__dict__.keys(): | |
return self.__dict__[attr] | |
else: | |
try: | |
out = self[attr] | |
if isinstance(out, dict): | |
out = AccessorDict(out) | |
return out | |
except KeyError: | |
return default | |
def __setattr__(self, attr, val): | |
raise NotImplementedError, "cannot write to AccessorDict instances!" | |
# make a nested dict structure (generally json->dict makes these messes) | |
d = { | |
'x': { | |
'y': { | |
'z': 'IT WORKS!' | |
} | |
} | |
} | |
# wrap the dict | |
ad = AccessorDict(d) | |
# you can use dotted notation to decend the keys | |
print ad.x.y.z | |
# you can still use regular notation too | |
print ad['x']['y']['z'] | |
# you can also mix them | |
print ad.x.y['z'] | |
print ad['x'].y.z | |
# you can also use get with them for defaults | |
print ad.x.y.get('z', 'default') # key present | |
print ad.x.y.get('zzz', 'default') # key absent | |
# you cannot write to keys at any level | |
ad.x.y.z = 20 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment