python 如何动态检查GenericAlias(Type)对象以确定其包含的类型?

r6vfmomb  于 2023-04-19  发布在  Python
关注(0)|答案(1)|浏览(105)

我有一个带有类型化tuple字段的数据类,我想动态查看它们元素的类型。当我打印类型时,我将它们视为容器(其内容正是我想要的):

from dataclasses import dataclass, fields

@dataclass
class TupleContainer:
    tuple2: tuple[float, str]
    tuple1: tuple[int, ...]

for field in fields(TupleContainer):
    t = field.type
    print(repr(t)) 

    # prints:
    # tuple[float, str]
    # tuple[int, ...]

但是当我尝试迭代或者索引到t时,我得到TypeError: 'types.GenericAlias' object is not iterable或者TypeError: There are no type variables left in tuple[float, str]
看起来这应该是可能的,但是我没有阅读到PEP或文档。

eeq64g8w

eeq64g8w1#

__args__就是我想要的!

from dataclasses import dataclass, fields

@dataclass
class TupleContainer:
    tuple2: tuple[float, str]
    tuple1: tuple[int, ...]

for field in fields(TupleContainer):
    t = field.type
    print(repr(t))
    print(t.__args__)

打印:

tuple[float, str]
(<class 'float'>, <class 'str'>)
tuple[int, ...]
(<class 'int'>, Ellipsis)

相关问题