Skip to content

Instantly share code, notes, and snippets.

@rsgalloway
Created January 17, 2015 02:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsgalloway/107efbef258a28470bdb to your computer and use it in GitHub Desktop.
Save rsgalloway/107efbef258a28470bdb to your computer and use it in GitHub Desktop.
dotdictify.py
class dotdictify(dict):
"""
life = {
'bigBang': {
'stars': {
'planets': {}
}
}
}
>>> life = dotdictify(life)
>>> print life.bigBang.stars.planets
>>> life.bigBang.stars.planets.earth = {'singleCellLife': 1}
>>> print life.bigBang.stars.planets
>>> print life.bigBang.stars.planets.earth.singleCellLife
"""
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