Skip to content

Python · maintainability

prefer-struct-over-namedtuple

python:prefer-struct-over-namedtuple

`collections.namedtuple` creates an untyped, positionally constructed record.

Code
SARJ015
Default
error
Fix
none
Languages
python

Why

Typed record declarations expose field types and make construction and review less error-prone.

Fix

Declare a `typing.NamedTuple` class or use a frozen pydantic model for boundary values.

Before / after

Executed by this rule’s unit tests.

Before

Functional untyped namedtuple

models.py · focus
import collections

Row = collections.namedtuple('Row', ['id', 'name'])

After

Typed NamedTuple declaration

models.py · focus
from typing import NamedTuple

class Row(NamedTuple):
    id: int
    name: str

Limits

  • Only imports from `collections` and qualified calls through `collections` bindings are reported.
  • Tests, `typing.NamedTuple`, unrelated attributes, and unbound bare calls are excluded.