Munch
Munch is a Python library providing a dot-accessible dictionary, similar to JavaScript objects. It's a widely used package in the Python ecosystem for handling configuration and data with intuitive attribute-style access. Actively maintained, it currently stands at version 4.0.0 with a steady release cadence.
Warnings
- breaking Version 3.0.0 introduced a breaking change requiring Python 3.6 or newer. Older Python versions (Python 2.7 and early Python 3) are no longer supported.
- breaking In version 3.0.0, the internal mechanism for version retrieval switched from `pkg_resources` to `importlib.metadata`. While primarily an internal change, this could affect projects that had implicit dependencies on `pkg_resources` being available via `munch`.
- breaking Version 4.0.0 removed the `six` compatibility library dependency. This change is unlikely to affect most direct users, but it means `six` is no longer implicitly installed or available through `munch`.
- gotcha The `Munch()` constructor performs only a shallow conversion of nested dictionaries. If you initialize a `Munch` with a dictionary containing other dictionaries, those nested dictionaries will remain standard `dict` objects and not become `Munch` objects themselves. To achieve recursive conversion, use the `munchify()` function.
- gotcha When `PyYAML` is installed, `Munch` objects automatically register themselves with YAML representers. This can lead to `!munch.Munch` tags appearing in YAML output, which might not be desired for cross-language compatibility or readability.
Install
-
pip install munch
Imports
- Munch
from munch import Munch
- DefaultMunch
from munch import DefaultMunch
- DefaultFactoryMunch
from munch import DefaultFactoryMunch
- RecursiveMunch
from munch import RecursiveMunch
- munchify
from munch import munchify
- unmunchify
from munch import unmunchify
Quickstart
from munch import Munch, munchify, DefaultMunch
# 1. Basic Munch object
data = Munch()
data.name = "Alice"
data.age = 30
print(f"Name: {data.name}, Age: {data.age}")
# Munch supports dictionary-style access too
data['city'] = 'New York'
print(f"City: {data.city}")
# 2. Initializing from a dictionary (shallow conversion)
regular_dict = {'user': {'id': 101, 'status': 'active'}}
m_shallow = Munch(regular_dict)
print(f"Type of nested 'user' in shallow Munch: {type(m_shallow.user)}") # Will be <class 'dict'>
# 3. Recursive conversion using munchify()
m_deep = munchify(regular_dict)
print(f"Type of nested 'user' in deep Munch: {type(m_deep.user)}") # Will be <class 'munch.Munch'>
print(f"User ID: {m_deep.user.id}")
# 4. DefaultMunch for default values
default_munch = DefaultMunch(0)
default_munch.count = 5
print(f"Existing count: {default_munch.count}") # Output: Existing count: 5
print(f"Non-existent value: {default_munch.non_existent}") # Output: Non-existent value: 0