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.
Multidict is dict-like collection of key-value pairs where key might be occurred more than once in the container.

multidict Multidict is dict-like collection of key-value pairs where key might be occurred more than once in the container. Introduction HTTP Headers

aio-libs 325 Dec 27, 2022
Persistent dict, backed by sqlite3 and pickle, multithread-safe.

sqlitedict -- persistent dict, backed-up by SQLite and pickle A lightweight wrapper around Python's sqlite3 database with a simple, Pythonic dict-like

RARE Technologies 954 Dec 23, 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
nocasedict - A case-insensitive ordered dictionary for Python

nocasedict - A case-insensitive ordered dictionary for Python Overview Class NocaseDict is a case-insensitive ordered dictionary that preserves the or

PyWBEM Projects 2 Dec 12, 2021
Supporting information (calculation outputs, structures)

Supporting information (calculation outputs, structures)

Eric Berquist 2 Feb 02, 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
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
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
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 JSON-friendly data structure which allows both object attributes and dictionary keys and values to be used simultaneously and interchangeably.

A JSON-friendly data structure which allows both object attributes and dictionary keys and values to be used simultaneously and interchangeably.

Peter F 93 Dec 01, 2022
My solutions to the competitive programming problems on LeetCode, USACO, LintCode, etc.

This repository holds my solutions to the competitive programming problems on LeetCode, USACO, LintCode, CCC, UVa, SPOJ, and Codeforces. The LeetCode

Yu Shen 32 Sep 17, 2022
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
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
🔬 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
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
Solutions for leetcode problems.

Leetcode-solution This is an repository for storring new algorithms that I am learning form the LeetCode for future use. Implemetations Two Sum (pytho

Shrutika Borkute 1 Jan 09, 2022
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 09, 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 03, 2022
Al-Quran dengan Terjemahan Indonesia

Al-Quran Rofi Al-Quran dengan Terjemahan / Tafsir Jalalayn Instalasi Al-Quran Rofi untuk Archlinux untuk pengguna distro Archlinux dengan paket manage

Nestero 4 Dec 20, 2021
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