mirror of
https://github.com/astral-sh/ruff.git
synced 2026-05-06 08:56:57 -04:00
a1bd94d0f6
## Summary
Per the spec:
> A named tuple class can be subclassed, but any fields added by the
subclass are not considered part of the named tuple type. Type checkers
should enforce that these newly-added fields do not conflict with the
named tuple fields in the base class.
The spec then provides this example:
```python
class Point(NamedTuple):
x: int
y: int
units: str = "meters"
class PointWithName(Point):
name: str # OK
x: int # Type error (invalid override of named tuple field)
```
We take a slightly more expansive view here, rejecting any attributes
(with or without an annotation, with or without a default) and
properties in a `NamedTuple` subclass. This seems to match Pyright and
Pyrefly, though Mypy doesn't flag these.
Shadowing an attribute in this way leads to odd behavior that is
probably never what you want, e.g.:
```python
from typing import NamedTuple
class A(NamedTuple):
x: int
class B(A):
x: int = 42
b = B(1)
print(b.x) # 42
print(b[0]) # 1
print(repr(b)) # B(x=1)
b.x = 99
print(b.x) # 99
print(b[0]) # 1
print(repr(b)) # B(x=1)
```