Skip to content

Instantly share code, notes, and snippets.

@lambdalisue
Created May 16, 2011 08:02
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 lambdalisue/974074 to your computer and use it in GitHub Desktop.
Save lambdalisue/974074 to your computer and use it in GitHub Desktop.
Attribute accessable dictionary for Python
class Attrdict(dict):
"""Attribute accessible dictionary class
Usage:
>>> attrdict = Attrdict(alice='in the wonderland')
>>> attrdict.alice
'in the wonderland'
>>> attrdict['hello'] = 'world'
>>> attrdict['hello']
'world'
>>> attrdict.hello
'world'
>>> attrdict.hello = 'madam'
>>> attrdict.hello
'madam'
>>> attrdict.foobar = 'hogehoge'
>>> attrdict.foobar
'hogehoge'
Reference:
http://code.activestate.com/recipes/389916-example-setattr-getattr-overloading/
"""
def __getattr__(self, key):
try:
return self.__getitem__(key)
except KeyError:
raise AttributeError(key)
def __setattr__(self, key, value):
if key in self:
super(Attrdict, self).__setattr__(key, value)
else:
self.__setitem__(key, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment