Last active
February 6, 2019 12:56
-
-
Save mironovdm/783b7f28119b87f22e02f53c6ef61ebc to your computer and use it in GitHub Desktop.
Dictionary with accessing keys like an attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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