Inspect generic python type of dataclass

Viewed 2286

For the given python code:

from dataclasses import dataclass
import typing


@dataclass
class Foo:
    bar: str


T = typing.TypeVar("T")


@dataclass
class Bar(typing.Generic[T]):
    items: typing.List[T]


Buz = Bar[Foo]

How to know with python code which Buz class have generic type Foo ? Does exist inspection method for that ?

1 Answers

Using typing_inspect module permit it:

import typing

import typing_inspect

T = typing.TypeVar("T")


class Gen(typing.Generic[T]):
    pass


print(typing_inspect.is_generic_type(Gen))  # True
print(typing_inspect.is_generic_type(Gen[int]))  # True
print(typing_inspect.get_args(Gen[int]))  # (<class int>,)
Related