Skip to main content

Advanced Python dictionaries with dot notation access

Project description

BuildStatus License

Fork Notice

This is a fork of the original python-box library with enhanced notification capabilities.

New Features in This Fork:

  • Change Notifications: Box and BoxList objects support an on_change callback parameter that gets triggered whenever values are modified

  • Hierarchical Propagation: Changes in nested objects automatically propagate up to parent objects

  • Root Detection: The is_root parameter distinguishes between direct changes and propagated changes from nested objects

  • Modern Build System: Migrated to pyproject.toml and uv for dependency management while maintaining Cython optimization support

Notification System Usage:

from box import Box

def track_changes(obj, key, value, action, is_root):
    if is_root:
        print(f"Direct change: {key} = {value}")
    else:
        print(f"Nested change propagated: {key} changed")

# Create Box with change tracking
data = Box({
    'user': {'name': 'John', 'age': 30},
    'settings': ['theme', 'lang']
}, on_change=track_changes)

data.status = 'active'        # Triggers: Direct change: status = active
data.user.name = 'Jane'       # Triggers: Nested change propagated: user changed
data.settings.append('tz')    # Triggers: Nested change propagated: settings changed

For more details on the notification system, see the comprehensive test suite in test/test_notification.py.

Original Box Features

from box import Box

movie_box = Box({ "Robin Hood: Men in Tights": { "imdb stars": 6.7, "length": 104 } })

movie_box.Robin_Hood_Men_in_Tights.imdb_stars
# 6.7

Box will automatically make otherwise inaccessible keys safe to access as an attribute. You can always pass conversion_box=False to Box to disable that behavior. Also, all new dict and lists added to a Box or BoxList object are converted automatically.

There are over a half dozen ways to customize your Box and make it work for you.

Check out the new Box github wiki for more details and examples!

Install

Fork Installation

This fork is not published to PyPI. To use it, install directly from source:

# Clone this fork
git clone <your-fork-url>
cd Box

# Install with uv (recommended)
uv sync --all-extras
uv build  # Creates optimized wheel with Cython extensions

# Or install with pip in development mode
pip install -e .[all]

Build with Cython Optimization

This fork maintains full Cython optimization support:

# Install dependencies including Cython
uv sync --all-extras

# Build optimized wheel
uv build

# Install the built wheel
pip install dist/python_box-*.whl

Original Installation (upstream)

For the original python-box library without notification features:

pip install python-box[all]~=7.0 --upgrade

Install with selected dependencies

Box does not install external dependencies such as yaml and toml writers. Instead you can specify which you want, for example, [all] is shorthand for:

pip install python-box[ruamel.yaml,tomli_w,msgpack]~=7.0 --upgrade

But you can also sub out ruamel.yaml for PyYAML.

Check out more details on installation details.

Box 7 is tested on python 3.7+, if you are upgrading from previous versions, please look through any breaking changes and new features.

Optimized Version

Box has introduced Cython optimizations for major platforms by default. Loading large data sets can be up to 10x faster!

If you are not on a x86_64 supported system you will need to do some extra work to install the optimized version. There will be an warning of “WARNING: Cython not installed, could not optimize box” during install. You will need python development files, system compiler, and the python packages Cython and wheel.

Linux Example:

First make sure you have python development files installed (python3-dev or python3-devel in most repos). You will then need Cython and wheel installed and then install (or re-install with –force) python-box.

pip install Cython wheel
pip install python-box[all]~=7.0 --upgrade --force

If you have any issues please open a github issue with the error you are experiencing!

Overview

Box is designed to be a near transparent drop in replacements for dictionaries that add dot notation access and other powerful feature.

There are a lot of types of boxes to customize it for your needs, as well as handy converters!

Keep in mind any sub dictionaries or ones set after initiation will be automatically converted to a Box object, and lists will be converted to BoxList, all other objects stay intact.

Check out the Quick Start for more in depth details.

Notification System (Fork Feature)

This fork adds a comprehensive change notification system to Box and BoxList objects.

Basic Usage

Pass an on_change callback when creating a Box or BoxList:

def my_callback(obj, key, value, action, is_root):
    print(f"Change: {key} = {value} (action: {action}, is_root: {is_root})")

data = Box({'user': {'name': 'John'}}, on_change=my_callback)
data.user.name = 'Jane'  # Triggers callback

Callback Parameters

  • obj: The object where the callback was originally set (always the root)

  • key: The key/index that changed

  • value: The new value (or None for deletions)

  • action: Type of change ('set', 'delete', 'clear', 'append', 'insert', 'child_change')

  • is_root: True for direct changes, False for nested changes that propagated up

Change Types

  • Direct changes: is_root=True - modifications made directly to the root object

  • Propagated changes: is_root=False - modifications made to nested objects that bubble up

Supported Operations

All modification operations trigger notifications:

data = Box({}, on_change=callback)

# Set operations
data.key = 'value'              # action='set', is_root=True
data['key'] = 'value'           # action='set', is_root=True
data.update({'a': 1, 'b': 2})   # action='set', is_root=True (per key)

# Delete operations
del data.key                    # action='delete', is_root=True
data.pop('key')                 # action='delete', is_root=True
data.clear()                    # action='clear', is_root=True

# Nested changes
data.nested.value = 42          # action='child_change', is_root=False

BoxList Support

BoxList objects also support notifications:

items = BoxList([1, 2, 3], on_change=callback)

items.append(4)                 # action='append', is_root=True
items.insert(0, 0)              # action='insert', is_root=True
items[1] = 'new'                # action='set', is_root=True
items.pop()                     # action='pop', is_root=True
items.remove('new')             # action='remove', is_root=True
items.clear()                   # action='clear', is_root=True

Error Handling

Callback errors are silently caught to prevent disrupting normal operations:

def bad_callback(obj, key, value, action, is_root):
    raise Exception("Callback error!")

data = Box(on_change=bad_callback)
data.key = 'value'  # Works normally, error is ignored

Use Cases

  • Change tracking: Monitor all modifications to complex data structures

  • Validation: Implement custom validation logic on data changes

  • Persistence: Automatically save data when changes occur

  • Debugging: Log all changes for debugging purposes

  • Event systems: Trigger events based on data modifications

Performance Notes

  • Cython optimization is fully supported for notification-enabled objects

  • Callback overhead is minimal when no callback is set

  • Parent references are efficiently managed automatically

Box can be instantiated the same ways as dict.

Box({'data': 2, 'count': 5})
Box(data=2, count=5)
Box({'data': 2, 'count': 1}, count=5)
Box([('data', 2), ('count', 5)])

# All will create
# <Box: {'data': 2, 'count': 5}>

Box is a subclass of dict which overrides some base functionality to make sure everything stored in the dict can be accessed as an attribute or key value.

small_box = Box({'data': 2, 'count': 5})
small_box.data == small_box['data'] == getattr(small_box, 'data')

All dicts (and lists) added to a Box will be converted on insertion to a Box (or BoxList), allowing for recursive dot notation access.

Box also includes helper functions to transform it back into a dict, as well as into JSON, YAML, TOML, or msgpack strings or files.

Thanks

A huge thank you to everyone that has given features and feedback over the years to Box! Check out everyone that has contributed.

A big thanks to Python Software Foundation, and PSF-Trademarks Committee, for official approval to use the Python logo on the Box logo!

Also special shout-out to PythonBytes, who featured Box on their podcast.

License

MIT License, Copyright (c) 2017-2023 Chris Griffith. See LICENSE file.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python_box_notify-1.0.0.tar.gz (57.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

python_box_notify-1.0.0-cp312-cp312-macosx_11_0_arm64.whl (531.6 kB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

File details

Details for the file python_box_notify-1.0.0.tar.gz.

File metadata

  • Download URL: python_box_notify-1.0.0.tar.gz
  • Upload date:
  • Size: 57.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.12

File hashes

Hashes for python_box_notify-1.0.0.tar.gz
Algorithm Hash digest
SHA256 361a3e96fb42c0a4f05966739118ea5d71586fe3937ae725e324edd2dfaf88fc
MD5 e484b46d1828de64a868b2e1f7521284
BLAKE2b-256 adc0378359a73b0d7ebfd17229bb4f2bad34114abb7b34dcf9d9507199ae72cf

See more details on using hashes here.

File details

Details for the file python_box_notify-1.0.0-cp312-cp312-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for python_box_notify-1.0.0-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 22d490c51b3015afa406d2dd902c522422c51f8c79b6f4a7c40731b548b2749f
MD5 1b85cd8efaa01febc8905ec1f6ec3079
BLAKE2b-256 32f5debca26e0ffd3c46660b630aa874603dddf4c787a41216bef67b10d71e8e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page