Use dataclass instead of NamedTuple

Consider using the dataclass here instead for simplicity, performance gains, and consistency

The NamedTuple has some drawbacks such as Python allows accidentally compare NamedTuple to a tuple or namedtuple with the same number of fields:

That is probably unexpected behaviour, and can result in bugs. Additionally, NamedTuple are less flexible and more brittle than dataclass because:

  • There is no option for mutable NamedTuple.
  • Cannot specify default values for NamedTuple values.
  • No control which fields are used for __init__, __repr__, etc.
  • Cannot support combining fields by inheritance.

These drawbacks can be avoided by using a dataclass.

If our GitHub code review bot spots this issue in your pull request it gives this advice:

code-review-doctorbotsuggested changes just now
models.py
1
+
class FooBarClass(NamedTuple):
Suggested changes
-
class FooBarClass(NamedTuple):
+
@dataclass(frozen=True)
+
class FooBarClass:
    pass
Commit suggestion

Consider using the dataclass here instead for simplicity, performance gains, and consistency

Read more
2
+
    pass
Update models.py
We're your Python code review copilot. Get code improvements right in your pull request with our GitHub code review bot.

Configuring this check

Code Review Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code avoid-named-tuple in your pyproject.toml file.

Read more about configuring Code Review Doctor.