1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
|
[](https://pypi.python.org/pypi/munch/)
[](https://pypi.python.org/pypi/munch/)
[](https://pypi.python.org/pypi/munch/)
munch
==========
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:
```python
>>> 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:
```python
>>> list(b.keys())
['hello', 'foo']
```
Including ``update()``:
```python
>>> b.update({ 'ponies': 'are pretty!' }, hello=42)
>>> print(repr(b))
Munch({'hello': 42, 'foo': Munch({'lol': True}), 'ponies': 'are pretty!'})
```
As well as iteration:
```python
>>> [ (k,b[k]) for k in b ]
[('hello', 42), ('foo', Munch({'lol': True})), ('ponies', 'are pretty!')]
```
And "splats":
```python
>>> "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.
```python
>>> 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](http://pyyaml.org/wiki/PyYAML) installed, Munch attempts to register itself with the various YAML Representers so that Munches can be transparently dumped and loaded.
```python
>>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
>>> import yaml
>>> yaml.dump(b)
'!munch.Munch\nfoo: !munch.Munch\n lol: true\nhello: 42\nponies: are pretty!\n'
>>> yaml.safe_dump(b)
'foo:\n lol: true\nhello: 42\nponies: are pretty!\n'
```
In addition, Munch instances will have a ``toYAML()`` method that returns the YAML string using ``yaml.safe_dump()``. This method also replaces ``__str__`` if present, as I find it far more readable. You can revert back to Python's default use of ``__repr__`` with a simple assignment: ``Munch.__str__ = Munch.__repr__``. The Munch class will also have a static method ``Munch.fromYAML()``, which loads a Munch out of a YAML string.
Finally, Munch converts easily and recursively to (``unmunchify()``, ``Munch.toDict()``) and from (``munchify()``, ``Munch.fromDict()``) a normal ``dict``, making it easy to cleanly serialize them in other formats.
Default Values
--------------
``DefaultMunch`` instances return a specific default value when an attribute is missing from the collection. Like ``collections.defaultdict``, the first argument is the value to use for missing keys:
```python
>>> from munch import DefaultMunch
>>> undefined = object()
>>> b = DefaultMunch(undefined, {'hello': 'world!'})
>>> b.hello
'world!'
>>> b.foo is undefined
True
```
``DefaultMunch.fromDict()`` also takes the ``default`` argument:
```python
>>> undefined = object()
>>> b = DefaultMunch.fromDict({'recursively': {'nested': 'value'}}, undefined)
>>> b.recursively.nested == 'value'
True
>>> b.recursively.foo is undefined
True
```
Or you can use ``DefaultFactoryMunch`` to specify a factory for generating missing attributes. The first argument is the factory:
```python
>>> from munch import DefaultFactoryMunch
>>> b = DefaultFactoryMunch(list, {'hello': 'world!'})
>>> b.hello
'world!'
>>> b.foo
[]
>>> b.bar.append('hello')
>>> b.bar
['hello']
```
Miscellaneous
-------------
* It is safe to ``import *`` from this module. You'll get: ``Munch``, ``DefaultMunch``, ``DefaultFactoryMunch``, ``munchify`` and ``unmunchify``.
* Ample Tests. Just run ``pip install tox && tox`` from the project root.
Feedback
--------
Open a ticket / fork the project on [GitHub](http://github.com/Infinidat/munch).
|