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

Related tags

Data Structuresmunch
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.
Webtesting for course Data Structures & Algorithms

Selenium job to automate queries to check last posts of Module Data Structures & Algorithms Web-testing for course Data Structures & Algorithms Struct

1 Dec 15, 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 07, 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 HDF5-based python pickle replacement

Hickle Hickle is an HDF5 based clone of pickle, with a twist: instead of serializing to a pickle file, Hickle dumps to an HDF5 file (Hierarchical Data

Danny Price 450 Dec 21, 2022
This repo represents all we learned and are learning in Data Structure course.

DataStructure Journey This repo represents all we learned and are learning in Data Structure course which is based on CLRS book and is being taught by

Aprime Afr (Alireza Afroozi) 3 Jan 22, 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
IADS 2021-22 Algorithm and Data structure collection

A collection of algorithms and datastructures introduced during UoE's Introduction to Datastructures and Algorithms class.

Artemis Livingstone 20 Nov 07, 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 02, 2021
Google, Facebook, Amazon, Microsoft, Netflix tech interview questions

Algorithm and Data Structures Interview Questions HackerRank | Practice, Tutorials & Interview Preparation Solutions This repository consists of solut

Quan Le 8 Oct 04, 2022
This repo is all about different data structures and algorithms..

Data Structure and Algorithm : Want to learn data strutrues and algorithms ??? Then Stop thinking more and start to learn today. This repo will help y

Priyanka Kothari 7 Jul 10, 2022
CLASSIX is a fast and explainable clustering algorithm based on sorting

CLASSIX Fast and explainable clustering based on sorting CLASSIX is a fast and explainable clustering algorithm based on sorting. Here are a few highl

69 Jan 06, 2023
🔬 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
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
Datastructures such as linked list, trees, graphs etc

datastructures datastructures such as linked list, trees, graphs etc Made a public repository for coding enthusiasts. Those who want to collaborate on

0 Dec 01, 2021
A mutable set that remembers the order of its entries. One of Python's missing data types.

An OrderedSet is a mutable data structure that is a hybrid of a list and a set. It remembers the order of its entries, and every entry has an index number that can be looked up.

Elia Robyn Lake (Robyn Speer) 173 Nov 28, 2022
A simple tutorial to use tree-sitter to parse code into ASTs

A simple tutorial to use py-tree-sitter to parse code into ASTs. To understand what is tree-sitter, see https://github.com/tree-sitter/tree-sitter. Tr

Nghi D. Q. Bui 7 Sep 17, 2022
A collection of data structures and algorithms I'm writing while learning

Data Structures and Algorithms: This is a collection of data structures and algorithms that I write while learning the subject Stack: stack.py A stack

Dhravya Shah 1 Jan 09, 2022
An command-line utility that schedules your exams preparation routines

studyplan A tiny utility that schedules your exams preparation routines. You only need to specify the tasks and the deadline. App will output a iCal f

Ilya Breitburg 3 May 18, 2022
RLStructures is a library to facilitate the implementation of new reinforcement learning algorithms.

RLStructures is a lightweight Python library that provides simple APIs as well as data structures that make as few assumptions as possibl

Facebook Research 262 Nov 18, 2022
Simple spill-to-disk dictionary

Chest A dictionary that spills to disk. Chest acts likes a dictionary but it can write its contents to disk. This is useful in the following two occas

Blaze 59 Dec 19, 2022