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
A Munch is a Python dictionary that provides attribute-style access (a la JavaScript objects).

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 mai

Infinidat Ltd. 643 Jan 07, 2023
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
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
This repository contains code for CTF platform.

CTF-platform Repository for backend of CTF hosting website For starting the project first time : Clone the repo in which you have to work in your syst

Yash Jain 3 Feb 18, 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
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 09, 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
One-Stop Destination for codes of all Data Structures & Algorithms

CodingSimplified_GK This repository is aimed at creating a One stop Destination of codes of all Data structures and Algorithms along with basic explai

Geetika Kaushik 21 Sep 26, 2022
This repository is for adding codes of data structures and algorithms, leetCode, hackerrank etc solutions in different languages

DSA-Code-Snippet This repository is for adding codes of data structures and algorithms, leetCode, hackerrank etc solutions in different languages Cont

DSCSRMNCR 3 Oct 22, 2021
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 01, 2023
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
dict subclass with keylist/keypath support, normalized I/O operations (base64, csv, ini, json, pickle, plist, query-string, toml, xml, yaml) and many utilities.

python-benedict python-benedict is a dict subclass with keylist/keypath support, I/O shortcuts (base64, csv, ini, json, pickle, plist, query-string, t

Fabio Caccamo 799 Jan 09, 2023
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
schemasheets - structuring your data using spreadsheets

schemasheets - structuring your data using spreadsheets Create a data dictionary / schema for your data using simple spreadsheets - no coding required

Linked data Modeling Language 23 Dec 01, 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
An esoteric data type built entirely of NaNs.

NaNsAreNumbers An esoteric data type built entirely of NaNs. Installation pip install nans_are_numbers Explanation A floating point number is just co

Travis Hoppe 72 Jan 01, 2023
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
🔬 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
Supporting information (calculation outputs, structures)

Supporting information (calculation outputs, structures)

Eric Berquist 2 Feb 02, 2022