Clarifying NamedTuple inheritance in the typing spec

There are a few things re: NamedTuple inheritance in the typing spec that I’m hoping to clarify here. If we agree that the wording needs to be tweaked, I can submit a PR with the changes.

https://typing.readthedocs.io/en/latest/spec/namedtuples.html

The spec contains these two lines:

NamedTuple does not support multiple inheritance.

In Python 3.11 and newer, the class syntax supports generic named tuple classes.

The type error that gets thrown at runtime for named tuple multiple inheritance is:

class Unit(NamedTuple, object):
    pass

# TypeError: can only inherit from a NamedTuple type and Generic

This error does not appear when a class extends another named tuple class, it seems like it only appears when a class directly has NamedTuple in its base class list.

class A(NamedTuple):
    pass

class B(A, object):
    pass

# no runtime error

It also doesn’t specify what happens when a class inherits from two named tuple classes, like so:

>>> class Foo1(NamedTuple):
...     x: int 
... 
>>> class Foo2(NamedTuple):
...     y: int
... 
>>> class Foo3(Foo1, Foo2):
...     z: int 
... 
>>> Foo3._fields
('x',)

The error message also implies that a generic named tuple definition of using the old style is also valid, like so:

T = TypeVar('T')
class Unit(NamedTuple, Generic[T]):
    pass

# no runtime error

Seems like the spec could be more explicit about what’s allowed and what’s not allowed. Thoughts?

Possibly the spec should actually say less about these details rather than more. The role of the typing spec is to describe the typing features that type checkers are supposed to support (and what the behaviour of type checkers should be regarding those features). It’s not really the purpose of the typing spec to exhaustively describe how parts of the typing module work at runtime. That information is more suited to the typing-module API reference in the CPython docs, and possibly HOWTO guides in Type System Guides — typing documentation.

1 Like