Last active
May 29, 2018 11:37
-
-
Save 0scarB/f6093efa6162029c3dfb4ea090f2056e to your computer and use it in GitHub Desktop.
Python data structure for working with a dict via attributes or keys
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 AttrDict: | |
def __init__(self, d=None, **kwargs): | |
for _dict in (d, kwargs): | |
if _dict: | |
for key, item in _dict.items(): | |
self._set(key, item) | |
def __str__(self): | |
return f'AttrDict({self.__dict__})' | |
def __repr__(self): | |
return str(self) | |
def __getitem__(self, key): | |
return self.__dict__[key] | |
def _set(self, key, item): | |
if type(item) is dict: | |
item = AttrDict(item) | |
self.__dict__[key] = item | |
def __setitem__(self, key, item): | |
self._set(key, item) | |
def __setattr__(self, key, item): | |
self._set(key, item) | |
def get(self, key, default=None): | |
try: | |
return self.__dict__[key] | |
except KeyError: | |
return default | |
if __name__ == '__main__': | |
d1 = AttrDict({'a': 1}) | |
d2 = AttrDict(a=1) | |
assert d1.a == d1['a'] == d2.a == d2['a'] == 1 | |
assert str(d1) == str(d2) == 'AttrDict({\'a\': 1})' | |
d = AttrDict({1: {'a': 'foo'}}) | |
assert d[1].a == 'foo' | |
assert str(d) == 'AttrDict({1: AttrDict({\'a\': \'foo\'})})' |
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment