A dot-accessible dictionary (a la JavaScript objects)
pip install munchmunch
Installation
pip install munch
Usage
munch is a fork of David Schoonover's Bunch package, providing similar functionality. 99% of the work was done by him, and the fork was made mainly for lack of responsiveness for fixes and maintenance on the original code.
Munch is a dictionary that supports attribute-style access, a la JavaScript:
>>> from munch import Munch
>>> b = Munch()
>>> b.hello = 'world'
>>> b.hello
'world'
>>> b['hello'] += "!"
>>> b.hello
'world!'
>>> b.foo = Munch(lol=True)
>>> b.foo.lol
True
>>> b.foo is b['foo']
True
Dictionary Methods
A Munch is a subclass of dict; it supports all the methods a dict does:
>>> list(b.keys())
['hello', 'foo']
Including update():
>>> b.update({ 'ponies': 'are pretty!' }, hello=42)
>>> print(repr(b))
Munch({'hello': 42, 'foo': Munch({'lol': True}), 'ponies': 'are pretty!'})
As well as iteration:
>>> [ (k,b[k]) for k in b ]
[('hello', 42), ('foo', Munch({'lol': True})), ('ponies', 'are pretty!')]
And "splats":
>>> "The {knights} who say {ni}!".format(**Munch(knights='lolcats', ni='can haz'))
'The lolcats who say can haz!'
Serialization
Munches happily and transparently serialize to JSON and YAML.
>>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
>>> import json
>>> json.dumps(b)
'{"foo": {"lol": true}, "hello": 42, "ponies": "are pretty!"}'
If JSON support is present (json or simplejson), Munch will have a toJSON() method which returns the object as a JSON string.
If you have PyYAML installed, Munch attempts to register itself with the various YAML Representers so that Munches can be transparently dumped and loaded.