Skip to content

typing.NamedTupleMeta should allow subclassing alongside classes other than NamedTuple and Generic #125167

@CoolCat467

Description

@CoolCat467

Feature or enhancement

Proposal:

I propose that typing.NamedTupleMeta should allow creation of NamedTuples that inherit from things other than NamedTuple or Generic.

For example,

from typing import NamedTuple

class BaseVector:
    """Shared functionality between all vectors."""
    ...

class Vector2(NamedTuple, BaseVector):
    """Vector2 Object. Takes an x and a y coordinate."""

    x: float
    y: float

class Vector3(NamedTuple, BaseVector):
    """Vector3 Object. Takes an x, y, and z coordinate."""

    x: float
    y: float
    z: float

Currently, if you try to do this, you get TypeError: can only inherit from a NamedTuple type and Generic being raised at runtime.

In particular, in typing, instead of this:

class NamedTupleMeta(type):
    def __new__(cls, typename, bases, ns):
        assert _NamedTuple in bases
        for base in bases:
            if base is not _NamedTuple and base is not Generic:
                raise TypeError(
                    'can only inherit from a NamedTuple type and Generic')
        ...

it would be changed to this:

class NamedTupleMeta(type):
    def __new__(cls, typename, bases, ns):
        if _NamedTuple not in bases:
             raise TypeError(
                 'must inherit from a NamedTuple type')
        ...

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

Kind of related but not really: #77258

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions