Skip to content

Instantly share code, notes, and snippets.

@flopezluis
Created December 2, 2011 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flopezluis/1423724 to your computer and use it in GitHub Desktop.
Save flopezluis/1423724 to your computer and use it in GitHub Desktop.
Simple but useful
class DictAsMember(dict):
def __getattr__(self, name):
"""
From : http://docs.python.org/reference/datamodel.html#object.__getattr__
Called when an attribute lookup has not found the attribute in the usual places
(i.e. it is not an instance attribute nor is it found in the class tree for self).
name is the attribute name
http://stackoverflow.com/questions/8709975/overwrite-in-python
"""
value = self[name]
if isinstance(value, dict):
value = DictAsMember(value)
return value
>>> my = DictAsMember()
>>> my["item"] = 3
>>> my.item
3
>>> my["item"]
3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment