Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inspect generic python type of dataclass

Tags:

python

typing

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 ?

like image 880
bux Avatar asked Oct 18 '25 11:10

bux


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>,)
like image 185
bux Avatar answered Oct 20 '25 00:10

bux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!