Skip to content

prefer-struct-over-namedtuple

Prefer typed declarations for static application-owned collections.namedtuple records.

Why

A static collections.namedtuple factory declares field names but cannot declare their types.

Fix

Use a class-based typing.NamedTuple when tuple behavior is part of the contract. Use a frozen, slotted dataclass or an existing validation model only when changing tuple semantics is safe.

Examples

Before — flagged Static record omits field types
models.py
from collections import namedtuple
Row = namedtuple("Row", ["id", "name"])
After — preferred Typed tuple-compatible record
models.py
from typing import NamedTuple
class Row(NamedTuple):
id: int
name: str
row = Row(1, "Ada")
id, name = row