Created
February 5, 2013 19:48
-
-
Save ngoffee/4717063 to your computer and use it in GitHub Desktop.
Dict whose items can also be accessed as attributes. This is the trivial implementation suggested by Martin Miller on
StackExchange: http://code.activestate.com/recipes/576972-attrdict/
with my own doctests.
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(dict): | |
"""Dict whose items can also be accessed as attributes. | |
This is the trivial implementation suggested by Martin Miller on | |
StackExchange: http://code.activestate.com/recipes/576972-attrdict/ | |
>>> ad = AttrDict() | |
Normal dict access: | |
>>> ad['foo'] = 3 | |
>>> ad['foo'] | |
3 | |
But key 'foo' can also be accessed as an attribute: | |
>>> ad.foo | |
3 | |
You can set keys via attribute access too: | |
>>> ad.bar = 4 | |
>>> ad.bar | |
4 | |
And then access them as dictionary keys: | |
>>> ad['bar'] | |
4 | |
>>> ad.bar | |
4 | |
Key lookup failure results in a KeyError: | |
>>> ad['baz'] | |
Traceback (most recent call last): | |
... | |
KeyError: 'baz' | |
While attribute lookup failure results in an AttributeError: | |
>>> ad.baz | |
Traceback (most recent call last): | |
... | |
AttributeError: 'AttrDict' object has no attribute 'baz' | |
""" | |
def __init__(self, *args, **kwargs): | |
super(AttrDict, self).__init__(*args, **kwargs) | |
self.__dict__ = self | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment