Skip to content

Instantly share code, notes, and snippets.

@mironovdm
Last active February 6, 2019 12:56
Show Gist options
  • Save mironovdm/783b7f28119b87f22e02f53c6ef61ebc to your computer and use it in GitHub Desktop.
Save mironovdm/783b7f28119b87f22e02f53c6ef61ebc to your computer and use it in GitHub Desktop.
Dictionary with accessing keys like an attributes
class DictWithAttributeAccess(dict):
def __getattr__(self, key):
return self[key]
def __setattr__(self, key, value):
self[key] = value
class AttrDict:
def __init__(self, params_dict):
self.__dict__['_d'] = self.parse(params_dict)
def parse(self, d: dict):
for k, v in d.items():
if isinstance(v, dict):
d[k] = self.parse(v)
return DictWithAttributeAccess(d)
def __getattr__(self, item):
return self._d[item]
def __setattr__(self, key, value):
self._d[key] = value
d = AttrDict({"hello": "world", {"subdictkey": "value"}})
d.hello.subdictkey
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment