Skip to content

Specialization of namedtuple types #92107

Closed
@serhiy-storchaka

Description

@serhiy-storchaka

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:

  1. Forbid subscription of types created by namedtuple(). If you want to add type annotations, use typing.NamedTuple.
  2. Add __class_getitem__ which checks that the number of types corresponds to the size of the named tuple.

@rhettinger

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions