A Munch is a Python dictionary that provides attribute-style access (a la JavaScript objects).

Overview

Build Status Latest Version Supported Python versions Downloads

munch

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:

>> b.hello 'world!' >>> b.foo = Munch(lol=True) >>> b.foo.lol True >>> b.foo is b['foo'] True ">
>>> 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.

>>> 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:

>>> 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:

>>> 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:

>>> 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.

Comments
  • What are the recommended type annotations?

    What are the recommended type annotations?

    Suppose I have this:

    from munch import munchify
    
    
    def gen_dict():
        return munchify({'foo': 'bar', 'id': 123})    
    

    What is the recommended way to type annotate the return value of gen_dict()? Simply munch.Munch?

    opened by MartinThoma 9
  • Please publish python universal wheel

    Please publish python universal wheel

    What are wheels? Wheels are the new standard of Python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.

    Advantages of wheels Faster installation for pure Python and native C extension packages. Avoids arbitrary code execution for installation. (Avoids setup.py) Installation of a C extension does not require a compiler on Windows or macOS. Allows better caching for testing and continuous integration. Creates .pyc files as part of installation to ensure they match the Python interpreter used. More consistent installs across platforms and machines.

    https://pythonwheels.com/

    Must appreciated!

    opened by pabelanger 8
  • __setattr__ will now munchify() any provided dict

    __setattr__ will now munchify() any provided dict

    I'm not sure if this is the best way to go about it, but I need Munch to munchify any dicts it is assigned:

    >>> from munch import *
    >>> m = Munch()
    >>> m.foo = {'bar':'baz'}
    >>> m
    Munch({'foo': Munch({'bar': 'baz'})})
    >>> m.foo.bar
    'baz'
    
    opened by kbni 8
  • Added DefaultMunch, which returns a special value for missing attributes

    Added DefaultMunch, which returns a special value for missing attributes

    Added a subclass of Munch: DefaultMunch, which returns a user-defined value when a requested key is not in the collection. The interface and behaviour is similar to collections.defaultdict, except that:

    • Only a constant value is returned; there is no default_factory method.
    • Retrieval of a missing value does not change the size of the collection.

    DefaultMuch.__default__ is a special attribute that won't be stored in the dictionary.

    The construction signature is based on defaultdict, where the default value is the first argument:

    b = DefaultMunch(default, {})
    

    This seemed cleaner than having a special keyword argument like _default=foo or so. However, the signature of fromDict is different, since it didn't already take any keyword arguments:

    b = DefaultMunch.fromDict({}, default=default)
    

    This PR supercedes #15. To get similar behaviour to undefined, a sentinel can be used as the default value of DefaultMunch.

    opened by z0u 8
  • support recursive munching

    support recursive munching

    from munch import Munch
    
    d = {'hello_world': {'cooldown': 30,
                     'items_per_replica': 3,
                     'replicas': {'max': 6, 'min': 3}},
     }
    m = Munch(d)
    m.hello_world.replicas.min
    
    Traceback (most recent call last):
      File "test.py", line 8, in <module>
        m.hello_world.replicas.min
    AttributeError: 'dict' object has no attribute 'replicas'
    
    opened by tf42src 7
  • Added JavaScript-like `undefined` behaviour for missing attributes

    Added JavaScript-like `undefined` behaviour for missing attributes

    Added a sub-class of Munch, UMunch, which returns undefined for missing attributes. You can use it like this:

    b = UMunch()
    b.foo = 1
    assert b.foo == 1
    assert b.bar is undefined
    
    # This does not raise an exception:
    if b.bar == 2:
         ...
    

    munchify has been changed to take an optional factory argument, which defaults to Munch. Munch.fromDict is now a class method, and returns the appropriate type (i.e. UMunch.fromDict returns a UMunch object). Tests have been updated.

    The behaviour of __getitem__ has not been changed. It could be made to return undefined for missing keys; I don't feel strongly about it either way.

    I'm not sure if this feature is welcome, but I'm happy to discuss it.

    opened by z0u 5
  • Add backwards compatibility with bunch library

    Add backwards compatibility with bunch library

    For people who have "bunch" spread all over the codebase from the library, this adds the old Bunch/bunchify/unbunchify names that call Munch/munchify/unmunchify respectively. This allows having the change in code when switching to munch be restricted just to a library name change.

    opened by mbarrien 5
  • Added RecursiveMunch object.

    Added RecursiveMunch object.

    Hi,

    I felt the need to have a RecursiveMunch class, which is similar to DefaultFactoryMunch, except that it creates an instance of itself to generate values for missing keys, instead of a user-specified function.

    Regards,

    Guillaume Rochette

    opened by GuillaumeRochette 4
  • use toDict() with __dict__ custom getter to allow getting the dictionary via `vars(munch)`

    use toDict() with __dict__ custom getter to allow getting the dictionary via `vars(munch)`

    It would be great if the standard python vars(obj) and the __dict__ attributes are respected, so that Munch instances could be used in a standard way.

    The toDict() syntax is not standard, and causes the implementation to leak through abstraction layers.

    Thanks for this library!

    opened by geyang 4
  • There is no __dict__ attribute on an object that inherits from Munch

    There is no __dict__ attribute on an object that inherits from Munch

    If I define an object that inherits from Munch:

    class Foo(Munch): def init(self, bar): self.bar = bar

    and then do:

    myfoo = Foo("mybar")

    the resulting myfoo object has no dict attribute, so while I can do myfoo.toDict(), I can't do myfoo.dict which would be nice to allow it to be treated like any other object.

    @property def dict(self): return self.toDict()

    would allow myfoo.dict to work the same way as toDict()

    opened by bobh66 4
  • Deserializing a munchified object makes it an dict

    Deserializing a munchified object makes it an dict

    I am trying to create an Munch object and when I serialize it to JSON and deserialize it, I am getting an dict, rather than an object.

    a = Munch(status_code= 200, text= {'code': '1234'})

    a.status_code # result 200

    a_js=json.dumps(a)

    json.loads(a_js).status_code # AttributeError: 'dict' object has no attribute 'status_code'

    opened by kannangce 3
  • munchify broken?

    munchify broken?

    Here is a minimal working example, which is broken. Is this already fixed?

    munchify((1,2,[{'A': 'B'}])) Result: (1, 2, [Munch({'A': 'B'}), Munch({'A': 'B'})]) Expected: (1, 2, [Munch({'A': 'B'})])

    opened by OliverTED 0
  • Describe Installation / Link out to Pypi page

    Describe Installation / Link out to Pypi page

    Authenticate the munch Pypi page as an official distribution by mentioning it / linking to it in the readme.

    Another way to make the pypi namespace evident would be to add an Installation section that says pip install munch

    This creates easy confidence that pip's 'munch' is this munch, reducing concerns as we worry more about the providence of our dependencies.

    opened by banagale 0
  • A warning/error should be given if an element has the key

    A warning/error should be given if an element has the key "items"

    Suppose you have

    parent:
      items:
        - a```
    
    Then items cannot be accessed, since it is used for the internal Python iterator. A warning might be appropriate.
    opened by Tomen 0
  • _make is part of namedtuple's contract, not tuple

    _make is part of namedtuple's contract, not tuple

    I think these should read namedtuple:

    https://github.com/Infinidat/munch/blob/d0aeb06/munch/init.py#L461 https://github.com/Infinidat/munch/blob/d0aeb06/munch/init.py#L523

    Currently, if a custom class inherits from tuple and an instance ends up with a _make attribute, munch will call it when the __dict__ attribute is accessed. Unlikely to happen by chance, but munch also inserts itself into SafeLoader, so it should probably err on the defensive side.

    opened by marksteward 2
  • Undeclared dependency on setuptools (pkg_resources)

    Undeclared dependency on setuptools (pkg_resources)

    On a system without Setuptools pre-installed, munch fails on import:

    ~ $ pip-run munch -- -c "import munch"
    Collecting munch
      Using cached munch-2.5.0-py2.py3-none-any.whl (10 kB)
    Collecting six
      Using cached six-1.15.0-py2.py3-none-any.whl (10 kB)
    Installing collected packages: six, munch
    Successfully installed munch-2.5.0 six-1.15.0
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/var/folders/c6/v7hnmq453xb6p2dbz1gqc6rr0000gn/T/pip-run-y4m51iwb/munch/__init__.py", line 24, in <module>
        import pkg_resources
    ModuleNotFoundError: No module named 'pkg_resources'
    

    The project should remove use of pkg_resources or declare the dependency on setuptools.

    opened by jaraco 1
Releases(2.2.0)
Owner
Infinidat Ltd.
Scale to Win
Infinidat Ltd.
Svector (pronounced Swag-tor) provides extension methods to pyrsistent data structures

Svector Svector (pronounced Swag-tor) provides extension methods to pyrsistent data structures. Easily chain your methods confidently with tons of add

James Chua 5 Dec 9, 2022
Array is a functional mutable sequence inheriting from Python's built-in list.

funct.Array Array is a functional mutable sequence inheriting from Python's built-in list. Array provides 100+ higher-order methods and more functiona

null 182 Nov 21, 2022
A DSA repository but everything is in python.

DSA Status Contents A: Mathematics B: Bit Magic C: Recursion D: Arrays E: Searching F: Sorting G: Matrix H: Hashing I: String J: Linked List K: Stack

Shubhashish Dixit 63 Dec 23, 2022
Common sorting algorithims in Python

This a Github Repository with code for my attempts for commonly used sorting algorithims, tested on a list with 3000 randomly generated numbers.

Pratham Prasoon 14 Sep 2, 2021
pyprobables is a pure-python library for probabilistic data structures

pyprobables is a pure-python library for probabilistic data structures. The goal is to provide the developer with a pure-python implementation of common probabilistic data-structures to use in their work.

Tyler Barrus 86 Dec 25, 2022
Python collections that are backended by sqlite3 DB and are compatible with the built-in collections

sqlitecollections Python collections that are backended by sqlite3 DB and are compatible with the built-in collections Installation $ pip install git+

Takeshi OSOEKAWA 11 Feb 3, 2022
This repository is a compilation of important Data Structures and Algorithms based on Python.

Python DSA ?? This repository is a compilation of important Data Structures and Algorithms based on Python. Please make seperate folders for different

Bhavya Verma 27 Oct 29, 2022
Leetcode solutions - All algorithms implemented in Python 3 (for education)

Leetcode solutions - All algorithms implemented in Python 3 (for education)

Vineet Dhaimodker 3 Oct 21, 2022
This Repository consists of my solutions in Python 3 to various problems in Data Structures and Algorithms

Problems and it's solutions. Problem solving, a great Speed comes with a good Accuracy. The more Accurate you can write code, the more Speed you will

SAMIR PAUL 1.3k Jan 1, 2023
My notes on Data structure and Algos in golang implementation and python

My notes on DS and Algo Table of Contents Arrays LinkedList Trees Types of trees: Tree/Graph Traversal Algorithms Heap Priorty Queue Trie Graphs Graph

Chia Yong Kang 0 Feb 13, 2022
Python library for doing things with Grid-like structures

gridthings Python library for doing things with Grid-like structures Development This project uses poetry for dependency management, pre-commit for li

Matt Kafonek 2 Dec 21, 2021
A Python library for electronic structure pre/post-processing

PyProcar PyProcar is a robust, open-source Python library used for pre- and post-processing of the electronic structure data coming from DFT calculati

Romero Group 124 Dec 7, 2022
Programming of a spanning tree algorithm with Python : In depth first with a root node.

ST Algorithm Programming of a spanning tree algorithm with Python : In depth first with a root node. Description This programm reads informations abou

Mathieu Lamon 1 Dec 16, 2021
Data Structure With Python

Data-Structure-With-Python- Python programs also include in this repo Stack A stack is a linear data structure that stores items in a Last-In/First-Ou

Sumit Nautiyal 2 Jan 9, 2022
🔬 Fixed struct serialization system, using Python 3.9 annotated type hints

py-struct Fixed-size struct serialization, using Python 3.9 annotated type hints This was originally uploaded as a Gist because it's not intended as a

Alba Mendez 4 Jan 14, 2022
Final Project for Practical Python Programming and Algorithms for Data Analysis

Final Project for Practical Python Programming and Algorithms for Data Analysis (PHW2781L, Summer 2020) Redlining, Race-Exclusive Deed Restriction Lan

Aislyn Schalck 1 Jan 27, 2022
Basic sort and search algorithms written in python.

Basic sort and search algorithms written in python. These were all developed as part of my Computer Science course to demonstrate understanding so they aren't 100% efficent

Ben Jones 0 Dec 14, 2022
A Python implementation of red-black trees

Python red-black trees A Python implementation of red-black trees. This code was originally copied from programiz.com, but I have made a few tweaks to

Emily Dolson 7 Oct 20, 2022
Transfer style api - An API to use with Tranfer Style App, where you can use two image and transfer the style

Transfer Style API It's an API to use with Tranfer Style App, where you can use

Brian Alejandro 1 Feb 13, 2022
Nasdaq Cloud Data Service (NCDS) provides a modern and efficient method of delivery for realtime exchange data and other financial information. This repository provides an SDK for developing applications to access the NCDS.

Nasdaq Cloud Data Service (NCDS) Nasdaq Cloud Data Service (NCDS) provides a modern and efficient method of delivery for realtime exchange data and ot

Nasdaq 8 Dec 1, 2022