Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
CoolCat467 opened this issue Oct 9, 2024 · 1 comment
Labels
topic-typing type-feature A feature request or enhancement

Comments

@CoolCat467
Copy link

CoolCat467 commented Oct 9, 2024

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

@CoolCat467 CoolCat467 added the type-feature A feature request or enhancement label Oct 9, 2024
@AlexWaygood
Copy link
Member

Duplicate of #116241

@AlexWaygood AlexWaygood marked this as a duplicate of #116241 Oct 9, 2024
@AlexWaygood AlexWaygood closed this as not planned Won't fix, can't repro, duplicate, stale Oct 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic-typing type-feature A feature request or enhancement
Projects
None yet
Development

No branches or pull requests

2 participants