Kamyar
Kamyar

Reputation: 2674

How to use generic namedtuple in Python3.7/3.8?

I am trying to use Generic Named Tuple feature in Python 3.7 (and 3.8) but the interpreter raises an error. Am I using the bad way?

from typing import NamedTuple, TypeVar, Generic
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int


T = TypeVar("T")
class MyResult(NamedTuple, Generic[T]):
    Body: T
    Status: int


def func1() -> MyResult[Person]:
    return MyResult(Person('asghar',12), 200)

Raises the following error:

Traceback (most recent call last):
  File "/Users/kamyar/Documents/generic_named_tuple.py", line 16, in <module>
    def func1() -> MyResult[Type[Person]]:
TypeError: 'type' object is not subscriptable

Upvotes: 2

Views: 594

Answers (1)

Kamyar
Kamyar

Reputation: 2674

Thanks to @shynjax287 I used the workaround to fix the code:

from typing import NamedTuple, TypeVar, Generic, Type
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int


T = TypeVar("T")

class MyResult(NamedTuple):
    Body: T
    Status: int

class MyResultGeneric(MyResult, Generic[T]):
    pass


def func1() -> MyResultGeneric[Person]:
    return MyResultGeneric[Person](Person('asghar',12), 200)

print(func1().Body.name)

Even PyCharm knows the return types and auto-complete works fine!

Upvotes: 3

Related Questions