Created
May 2, 2014 19:12
-
-
Save fumingshih/49c1e04e1bee7caa06a9 to your computer and use it in GitHub Desktop.
This piece of python code converts python dictionary object to have access like object attributes
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 dotdictify(dict): | |
marker = object() | |
def __init__(self, value=None): | |
if value is None: | |
pass | |
elif isinstance(value, dict): | |
for key in value: | |
self.__setitem__(key, value[key]) | |
else: | |
raise TypeError, 'expected dict' | |
def __setitem__(self, key, value): | |
if isinstance(value, dict) and not isinstance(value, dotdictify): | |
value = dotdictify(value) | |
dict.__setitem__(self, key, value) | |
def __getitem__(self, key): | |
found = self.get(key, dotdictify.marker) | |
if found is dotdictify.marker: | |
found = dotdictify() | |
dict.__setitem__(self, key, found) | |
return found | |
__setattr__ = __setitem__ | |
__getattr__ = __getitem__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment