AttrDict
AttrDict is an MIT-licensed Python library (version 2.0.1) providing mapping objects that allow their elements to be accessed both as keys (like a standard dict) and as attributes. It aims to simplify the creation of hierarchical data structures, particularly useful for configuration objects. The project's last release was in 2019, and its GitHub repository was archived in the same year, indicating it is no longer actively maintained.
Warnings
- breaking The `attrdict` library is incompatible with Python 3.10 and newer versions. It relies on `from collections import Mapping`, which was removed in Python 3.10. Attempting to install or run `attrdict` on Python 3.10+ will result in an `ImportError`.
- deprecated The `attrdict` project is no longer actively maintained. Its GitHub repository was archived in February 2019, and it has not received updates since then. It is not recommended for new projects.
- gotcha When accessing nested dictionaries via attribute access (e.g., `attr.foo.bar`), `AttrDict` recursively converts internal dictionaries to `AttrDict` (or `AttrMap`) instances. Crucially, non-string sequence types (like lists) are *automatically converted to tuples* by default when accessed as an attribute.
- gotcha The `copy()` method of an `AttrDict` instance returns a standard Python `dict`, not another `AttrDict` instance.
- gotcha Unlike a standard `dict`, `AttrDict` does not clone the input dictionary upon creation. It uses the same dictionary instance internally. Modifying the original dictionary after creating an `AttrDict` from it will affect the `AttrDict` instance.
Install
-
pip install attrdict
Imports
- AttrDict
from attrdict import AttrDict
- AttrMap
from attrdict import AttrMap
- AttrDefault
from attrdict import AttrDefault
Quickstart
from attrdict import AttrDict
# Create an AttrDict from a regular dictionary
data = {'server': {'host': 'localhost', 'port': 8000}, 'debug': True}
settings = AttrDict(data)
# Access elements using attribute notation
print(f"Host: {settings.server.host}")
print(f"Port: {settings.server.port}")
# Attribute access for non-existent keys raises AttributeError
try:
print(settings.non_existent)
except AttributeError as e:
print(f"Error accessing non_existent attribute: {e}")
# Item access (like dict) still works
print(f"Debug setting: {settings['debug']}")