正在访问打字类型。列表

问题描述 投票:1回答:1

我目前正在编写代码,需要知道给定的类型注释是否可迭代(例如ta = typing.List[str]

我期待……像这样工作:

if isinstance(ta, typing.List):
    # do s.th.

但是,ta是typing._GenericAlias类型,与type.List没有多大关系。

相反,我必须像这样使用'origin'属性:

if getattr(ta, '__origin__', None) == list:
    # do s.th.

这真的是正确的方法吗?

python-3.x typing
1个回答
0
投票

在CPython 3.8中:

from typing import_GenericAlias

# Now, let's suppose that you have a class "cls"
name = "your_attribute"
typ = cls.__annotations__[name]
if isinstance(typ, _GenericAlias) and typ._name == "List":
    print("This is a list type")

_GenericAlias是一个未记录的受保护/生成的类。这是一个实现细节。我不知道在运行时访问类型信息的任何可靠方法。

© www.soinside.com 2019 - 2024. All rights reserved.