namedlist

1.8 · maintenance · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates creating a basic mutable namedlist, using global default values for fields, and correctly handling mutable default values (like lists) using the `FACTORY` function to ensure each instance gets its own independent mutable object.

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

view raw JSON →