Closed
Description
collections.namedtuple()
creates a tuple
subclass, and as a subclass it inherits all tuple
methods, including __class_getitem__
.
The __new__
method has been overridden in a named tuple class. It no longer accept an iterator of arbitrary length. The named tuple has fixed number of elements, and the constructor accept fixed number of arguments (some may be optional).
But the __class_getitem__
is inherited from tuple
. It allows to specialize the named tuple type with arbitrary number of arguments.
Point2D = namedtuple('Point2D', 'x y label')
Point2D[int, int, str]
Point2D[int, str]
Point2D[int, ...]
It looks confusing at best. A named tuple is not a general tuple, it cannot have an arbitrary number of items.
There are two options:
- Forbid subscription of types created by
namedtuple()
. If you want to add type annotations, usetyping.NamedTuple
. - Add
__class_getitem__
which checks that the number of types corresponds to the size of the named tuple.