Skip to content

Instantly share code, notes, and snippets.

@sujeetkv
Last active July 6, 2019 02:29
Show Gist options
  • Save sujeetkv/5e53d229fcc73a3f20cea1a7d2c22cdc to your computer and use it in GitHub Desktop.
Save sujeetkv/5e53d229fcc73a3f20cea1a7d2c22cdc to your computer and use it in GitHub Desktop.
Make a dictionary behave like an object, with attribute-style access.
class DictObject(dict):
"""Dict behaving like an object, with attribute-style access."""
__strict_attr__ = True
__attr_default__ = None
def __getattr__(self, name):
try:
return self[name]
except KeyError:
if self.__strict_attr__:
raise AttributeError(name)
else:
return self.__attr_default__
def __setattr__(self, name, value):
if name not in ('__strict_attr__', '__attr_default__'):
self[name] = value
class MyDict(DictObject):
pass
d = MyDict(one=1, two=2)
print(d.one)
print(d['one'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment