I saw @ yutaka2487's "Allow Python dictionary to be accessed as an attribute" and it seemed that it could be done by another method, so I tried it. I tried it.
It's a simple way to turn the dictionary itself (self
) into an attribute dictionary (__dict__
).
All the tests were ok, but if you have any pitfalls, please comment.
attrdict.py
class attrdict(dict):
'''A dictionary that can also access attributes using its keyword.
>>> ad = attrdict(a=1, b=2)
>>> sorted(ad.items())
[('a', 1), ('b', 2)]
>>> ad['a'], ad.a
(1, 1)
>>> ad['b'], ad.b
(2, 2)
>>> ad['a'] = 3
>>> ad['a'], ad.a
(3, 3)
>>> ad.b = 4
>>> ad['b'], ad.b
(4, 4)
>>> ad['c'] = 5
>>> ad['c'], ad.c
(5, 5)
>>> ad.d = 6
>>> ad['d'], ad.d
(6, 6)
>>> sorted(ad.items())
[('a', 3), ('b', 4), ('c', 5), ('d', 6)]
'''
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
if __name__ == '__main__':
import doctest
doctest.testmod()
test results
$ python attrdict.py -v
Trying:
ad = attrdict(a=1, b=2)
Expecting nothing
ok
Trying:
sorted(ad.items())
Expecting:
[('a', 1), ('b', 2)]
ok
Trying:
ad['a'], ad.a
Expecting:
(1, 1)
ok
Trying:
ad['b'], ad.b
Expecting:
(2, 2)
ok
Trying:
ad['a'] = 3
Expecting nothing
ok
Trying:
ad['a'], ad.a
Expecting:
(3, 3)
ok
Trying:
ad.b = 4
Expecting nothing
ok
Trying:
ad['b'], ad.b
Expecting:
(4, 4)
ok
Trying:
ad['c'] = 5
Expecting nothing
ok
Trying:
ad['c'], ad.c
Expecting:
(5, 5)
ok
Trying:
ad.d = 6
Expecting nothing
ok
Trying:
ad['d'], ad.d
Expecting:
(6, 6)
ok
Trying:
sorted(ad.items())
Expecting:
[('a', 3), ('b', 4), ('c', 5), ('d', 6)]
ok
2 items had no tests:
__main__
__main__.attrdict.__init__
1 items passed all tests:
13 tests in __main__.attrdict
13 tests in 3 items.
13 passed and 0 failed.
Test passed.