Skip to content

Instantly share code, notes, and snippets.

Created December 21, 2012 14:17
Show Gist options
  • Save anonymous/4353090 to your computer and use it in GitHub Desktop.
Save anonymous/4353090 to your computer and use it in GitHub Desktop.
Simple class to make dictionary able to use attribute get operation to get elements it contains using syntax like: >>> d = AttrDict(arg1=1, arg2='hello') >>> print d.arg1 1 >>> print d.arg2 hello >>> print d['arg2'] hello >>> print d['arg1'] 1
class AttrDict(dict):
""" Simple class to make dictionary able to use attribute get operation
to get elements it contains using syntax like:
>>> d = AttrDict(arg1=1, arg2='hello')
>>> print d.arg1
1
>>> print d.arg2
hello
>>> print d['arg2']
hello
>>> print d['arg1']
1
"""
def __getattribute__(self, name):
try:
return super(AttrDict, self).__getattribute__(name)
except AttributeError:
try:
return super(AttrDict, self).__getitem__(name)
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
self[name] = value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment