nattrs 
Nested attributes utility functions for python. Allows getting/setting of object attributes and dict members interchangeably. Useful to populate nested dicts for storing outputs of a loop.
The functions should work with most dict types (i.e. Mapping / MutableMapping) and classes.
Tip: Attribute names can be found using regular expressions.
Installation
Install from PyPI:
pip install nattrs
Install from GitHub:
python -m pip install git+https://github.com/ludvigolsen/nattrs
Main functions
| Class/Function | Description |
|---|---|
nested_getattr |
Get object attributes/dict members recursively, given by dot-separated names. |
nested_setattr |
Set object attribute/dict member by recursive lookup, given by dot-separated names. |
nested_mutattr |
Apply function (mutate) to nested object attribute/dict member. |
nested_updattr |
Update dict / class.dict of nested attributes. |
nested_hasattr |
Check whether recursive object attributes/dict members exist. |
nested_delattr |
Delete nested object attributes/dict members. |
populate_product |
Create and populate nested dicts with specified layers and the same leaf value. |
Examples
Create class B with a dict c with the member d:
class B:
def __init__(self):
self.c = {
"d": 1
}
Add to a dict a:
a = {"b": B()}
nested_getattr
Get the value of d:
nested_getattr(a, "b.c.d")
>> 1
Get default value when not finding an attribute:
nested_getattr(a, "b.o.p", default="not found")
>> "not found"
nested_setattr
Set the value of d:
nested_setattr(a, "b.c.d", 2)
Check new value of d:
nested_getattr(a, "b.c.d")
>> 2
nested_mutattr
Mutate d with an anonymous function (lambda):
nested_mutattr(a, "b.c.d", lambda x: x * 5)
Check new value of d:
nested_getattr(a, "b.c.d")
>> 10
Note: If your function performs the assignment in-place, remember to enable the is_inplace_fn argument.
nested_updattr
Update d with a dictionary:
nested_updattr(a, "b.c.d", {"d": 3})
Check new value of d:
nested_getattr(a, "b.c.d")
>> 3
Note: Also work on class.__dict__ dicts.
nested_hasattr
Check presence of the member 'd':
nested_hasattr(a, "b.c.d")
>> True
Fail to find member 'o':
nested_hasattr(a, "b.o.p")
>> False
nested_delattr
Delete the member 'd':
nested_delattr(a, "b.c.d")
nested_hasattr(a, "b.c.d")
>> False
Ignore that it fails to find member 'o':
nested_delattr(a, "b.o.p", allow_missing=True)
populate_product
In this example, we wish to pre-populate nested dicts with empty lists to allow appending within a for loop. First, we go through the manual approach of doing this. Second, we show how easy it is to do with populate_product().
Say we have 3 variables that can each hold 2 values. We want to compute something for each combination of these values. Let's first define these variables and their options:
animal = ["cat", "dog"]
food = ["strawberry", "cucumber"]
temperature = ["cold", "warm"]
Let's generate the product of these options:
import itertools
combinations = list(itertools.product(*[animal, food, temperature]))
combinations
>> [('cat', 'strawberry', 'cold'),
>> ('cat', 'strawberry', 'warm'),
>> ('cat', 'cucumber', 'cold'),
>> ('cat', 'cucumber', 'warm'),
>> ('dog', 'strawberry', 'cold'),
>> ('dog', 'strawberry', 'warm'),
>> ('dog', 'cucumber', 'cold'),
>> ('dog', 'cucumber', 'warm')]
Now we can create a nested dict structure with a list in the leaf element:
# Initialize empty dict
nested_dict = {}
for leaf in combinations:
# Join each string with dot-separation:
attr = ".".join(list(leaf))
# Assign empty list to the leafs
# `make_missing` creates dicts for each
# missing attribute/dict member
nattrs.nested_setattr(
obj=nested_dict,
attr=attr,
value=[],
make_missing=True
)
nested_dict
>> {'cat': {'strawberry': {'cold': [], 'warm': []},
>> 'cucumber': {'cold': [], 'warm': []}},
>> 'dog': {'strawberry': {'cold': [], 'warm': []},
>> 'cucumber': {'cold': [], 'warm': []}}}
This dict population is actually provided by populate_product(). Instead of an empty list, let's set the value to an "edibility" score that could be changed by a later function:
layers = [animal, food, temperature]
populate_product(
layers=layers,
val=False
)
>> {'cat': {'strawberry': {'cold': False, 'warm': False},
>> 'cucumber': {'cold': False, 'warm': False}},
>> 'dog': {'strawberry': {'cold': False, 'warm': False},
>> 'cucumber': {'cold': False, 'warm': False}}}
Metadata
Release files for nattrs 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| nattrs-0.3.0.tar.gz | 13.5 kB | Without provenance | Details for nattrs-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| nattrs-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for nattrs-0.3.0-py3-none-any.whl |
Total release size: 33.0 kB
Release files / nattrs-0.3.0.tar.gz
| Download URL | nattrs-0.3.0.tar.gz |
|---|---|
| Size | 13.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
10b329fdc5deb2c377080f93711d2fcdb412c932e8c8c8ceccf35f6f3982be3e
|
|
BLAKE2b-256 checksum How to use checksums |
73c16af086fb1dd528e070883d22f5f0ab5b06040dca28bb358ccf34c92fd42b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.0.1 CPython/3.9.6 Darwin/25.4.0
|
Release files / nattrs-0.3.0-py3-none-any.whl
| Download URL | nattrs-0.3.0-py3-none-any.whl |
|---|---|
| Size | 19.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
77f1bcc39e0cebc0c61a5ebb2be97708da3651ea3328c8e1197eb3bfaccba5fb
|
|
BLAKE2b-256 checksum How to use checksums |
0c5f02900a81818fd879a0fd097c46a66b6d7048e5c8e6d03d6392ed9caf8ae7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.0.1 CPython/3.9.6 Darwin/25.4.0
|
Security for nattrs 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.