namedlist
namedlist is a Python library that provides a factory function to create list-like objects with named fields, similar to `collections.namedtuple`, but with mutable instances. It also offers support for per-field default values and an optional default value for all fields. The current version is 1.8, released in August 2020. This package is no longer actively maintained, and the built-in `dataclasses` module is recommended for new projects.
Common errors
-
assert b.x == [4] # When 'x' was initialized with a default empty list in A
cause The default mutable object (e.g., a list) for a field was shared across all instances, meaning modifications to one instance's default affected others.fixWrap mutable default values with `FACTORY` when defining the `namedlist`. Example: `A = namedlist('A', [('x', FACTORY(list))])` instead of `A = namedlist('A', [('x', [])])`. -
AttributeError: 'Point' object has no attribute 'z' (when trying to assign p.z = 2)
cause `namedlist` uses `__slots__` by default, which restricts instance attributes to only the defined fields. Attempts to add new attributes after creation will fail.fixIf you require the ability to add arbitrary new attributes to instances, define the `namedlist` with `use_slots=False`: `Point = namedlist('Point', 'x y', use_slots=False)`.
Warnings
- deprecated The `namedlist` package is no longer actively maintained. For new projects, it is strongly recommended to use Python's built-in `dataclasses` module, which offers similar functionality with modern Python features and active development.
- gotcha When defining `namedlist.namedlist` fields with mutable default values (e.g., lists, dictionaries), all instances created will share the *same* mutable object, leading to unexpected side effects when one instance modifies it.
- gotcha By default, `namedlist.namedlist` classes use `__slots__` to optimize memory usage. This prevents adding new attributes to an instance after creation, resulting in an `AttributeError` if attempted.
Install
-
pip install namedlist
Imports
- namedlist
from namedlist import namedlist
- FACTORY
from namedlist import namedlist, FACTORY
Quickstart
from namedlist import namedlist, FACTORY
# Basic mutable namedlist
Point = namedlist('Point', 'x y')
p = Point(1, 3)
print(f"Initial point: {p}")
p.x = 2
print(f"Modified point: {p}")
assert p.x == 2
assert p.y == 3
# Namedlist with default values
Rect = namedlist('Rect', 'x1 y1 x2 y2', default=0)
r = Rect(x1=10, y1=10)
print(f"Rectangle with defaults: {r}")
assert r.x1 == 10 and r.y1 == 10 and r.x2 == 0 and r.y2 == 0
# Namedlist with a factory for mutable defaults (e.g., list)
Config = namedlist('Config', [('name', 'default'), ('options', FACTORY(list))])
c1 = Config(name='App1')
c1.options.append('verbose')
print(f"Config 1: {c1}")
c2 = Config(name='App2') # new instance, new list for options
print(f"Config 2: {c2}")
assert c1.options == ['verbose']
assert c2.options == [] # Demonstrates independent mutable defaults