簡體   English   中英

檢查數據類的通用 python 類型

[英]Inspect generic python type of dataclass

對於給定的 python 代碼:

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]

如何使用 python 代碼知道哪個Buz class 具有通用類型Foo 是否存在檢查方法?

使用typing_inspect模塊允許它:

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>,)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM