Skip to content

Instantly share code, notes, and snippets.

@fumingshih
Created May 2, 2014 19:12
Show Gist options
  • Save fumingshih/49c1e04e1bee7caa06a9 to your computer and use it in GitHub Desktop.
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
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