首页 > 解决方案 > 访问类型的类型。列表

问题描述

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

我期待着…… 像这样工作:

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

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

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

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

这真的是正确的方法吗?

标签: python-3.xtyping

解决方案


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


推荐阅读