Python Box
python-box is an active library that provides an advanced Python dictionary with dot notation access, allowing dictionary keys to be accessed as attributes. It simplifies working with deeply nested data structures and offers various serialization methods (JSON, YAML, TOML, JSON5, TOON) and other utility classes. The current version is 7.4.1, and it maintains a regular release cadence with updates and bug fixes.
Warnings
- breaking Support for older Python versions (3.8, 3.9) has been removed in recent major versions. Ensure your project runs on Python 3.10 or newer.
- breaking The `box_dots` functionality changed in v7.0.0. Keys containing periods (`.`) are now automatically treated as nested keys by default, potentially altering data structure interpretation for existing code.
- gotcha Serialization methods like `Box.from_yaml`, `Box.to_toml`, etc., require specific optional dependencies (e.g., `PyYAML`, `toml`) to be installed separately. Failing to install them will result in `ImportError`.
- breaking The signature for `default_function` when defining default behavior in `DefaultBox` was changed in v7.0.0, now including `box_instance` and `key` parameters.
Install
-
pip install python-box -
pip install python-box[all] -
pip install python-box[yaml,toml,json5,toon]
Imports
- Box
from box import Box
- ConfigBox
from box import ConfigBox
- DefaultBox
from box import DefaultBox
- BoxList
from box import BoxList
- ShorthandBox
from box import ShorthandBox
- BoxKeyError
from box import BoxKeyError
Quickstart
from box import Box
# Create a Box from a dictionary
config = Box({
'application': {
'name': 'MyAwesomeApp',
'version': '1.0.0',
'settings': {
'debug_mode': True,
'log_level': 'INFO'
}
},
'database': {
'host': 'localhost',
'port': 5432
}
})
# Access items using dot notation
print(f"App Name: {config.application.name}")
print(f"Debug Mode: {config.application.settings.debug_mode}")
# Modify items
config.database.port = 5433
print(f"New DB Port: {config.database.port}")
# Add new items
config.application.author = 'AI Agent'
print(f"App Author: {config.application.author}")
# Example with missing key (will raise AttributeError without default_box_create_on_get)
try:
print(config.non_existent_key)
except AttributeError as e:
print(f"Caught expected error: {e}")