python-3.x - 访问类型的类型。列表
问题描述
我目前正在编写代码,需要知道给定的类型注释是否是可迭代的(例如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.
这真的是正确的方法吗?
解决方案
在 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
是未记录的受保护/生成的类。这是一个实现细节。我不知道在运行时访问类型信息的任何可靠方法。
推荐阅读
- sql - 按年份排序为 nvarchar,然后按数字排序
- android - 快速入门指南有问题
- javascript - 无法从商店获取更新状态
- android - 如何在谷歌地图中显示附近的餐馆到当前用户位置。当用户打开地图活动时
- azure - Azure DevOps CI/CD 部署 Web 或 Function App 更改 YAML Pipelines 中 appsettings 中的值
- javascript - 使用哈希和过滤哈希遍历数组
- android - setText 显示为红色,我不明白为什么
- javascript - CodeHS JavaScript - 如何做一个一次性计时器?
- react-native - 在本机反应中显示 Base64 svg
- javascript - 停止活动流中的存档时出错