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.
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
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
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
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 high-performance immutable mapping type for Python.

immutables An immutable mapping type for Python. The underlying datastructure is a Hash Array Mapped Trie (HAMT) used in Clojure, Scala, Haskell, and

magicstack 996 Jan 02, 2023
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
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
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
Map single-cell transcriptomes to copy number evolutionary trees.

Map single-cell transcriptomes to copy number evolutionary trees. Check out the tutorial for more information. Installation $ pip install scatrex SCA

Computational Biology Group (CBG) 12 Jan 01, 2023
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
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
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
Decided to include my solutions for leetcode problems.

LeetCode_Solutions Decided to include my solutions for leetcode problems. LeetCode # 1 TwoSum First leetcode problem and it was kind of a struggle. Th

DandaIT04 0 Jan 01, 2022
Integrating C Buffer Data Into the instruction of `.text` segment instead of on `.data`, `.rodata` to avoid copy.

gcc-bufdata-integrating2text Integrating C Buffer Data Into the instruction of .text segment instead of on .data, .rodata to avoid copy. Usage In your

Jack Ren 1 Jan 31, 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
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
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
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
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
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

Tyler Barrus 86 Dec 25, 2022