[Python] Generic NamedTuple in python 3.7 [duplicate]

Discussão em 'Python' iniciado por Stack, Julho 10, 2025.

  1. Stack

    Stack Membro Participativo

    What is the correct way to define a Generic NamedTuple in using the typing module python 3.7?

    I can define

    from typing import TypeVar, Generic, NamedTuple

    T = TypeVar("T")

    class C(Generic[T], NamedTuple):
    """NameTuple and Generic ???"""
    x: T

    c = C(1)
    print(c) # prints "C(x=1)", as expected



    However, I cannot use the C[T] as a type hint:

    # raises TypeError: 'type' object is not subscriptable
    def f(c: C[int]):
    print("from f:", c)

    Continue reading...

Compartilhe esta Página