Last active
May 29, 2018 20:26
-
-
Save noamtm/9758122 to your computer and use it in GitHub Desktop.
Python: read-only access to dictionary keys as 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
# There are other solutions across the interwebs. This is one that avoids complexities | |
# because it's read-only (useful when you just want to read json data, for example). | |
# It also makes it possible to read nested dictionaries in the same way. | |
# Based on ideas from http://code.activestate.com/recipes/473786-dictionary-with-attribute-style-access/ | |
class attrdict (dict): | |
''' | |
Read-only access to dictionary keys as attributes. | |
>>> d=attrdict({"a":1, "b":2, "c":{"a":1, "b":2, "c":{"a":1, "b":2}}}) | |
>>> d.a | |
1 | |
>>> d.b | |
2 | |
>>> d.c | |
{'a': 1, 'c': {'a': 1, 'b': 2}, 'b': 2} | |
>>> d.c.a | |
1 | |
>>> d.c.c | |
{'a': 1, 'b': 2} | |
>>> d.c.c.a | |
1 | |
''' | |
def __getitem__(self, key): | |
value = dict.__getitem__(self, key) | |
return attrdict(value) if isinstance(value, dict) else value | |
__getattr__ = __getitem__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment