python - 如何获得 Python 3.7 新的数据类字段类型?
问题描述
Python 3.7 引入了称为数据类的新功能。
from dataclasses import dataclass
@dataclass
class MyClass:
id: int = 0
name: str = ''
在函数参数中使用类型提示(注解)时,您可以使用检查模块轻松获取注解类型。如何获取数据类字段类型?
解决方案
检查__annotations__
为您提供原始注释,但这些注释不一定对应于数据类的字段类型。像 ClassVar 和 InitVar 这样的东西会出现在 中__annotations__
,即使它们不是字段,并且继承的字段也不会出现。
相反,调用dataclasses.fields
数据类,并检查字段对象:
field_types = {field.name: field.type for field in fields(MyClass)}
也__annotations__
不会fields
解析字符串注释。如果要解析字符串注释,最好的方法可能是typing.get_type_hints
. get_type_hints
将包括 ClassVars 和 InitVars,所以我们fields
用来过滤掉它们:
resolved_hints = typing.get_type_hints(MyClass)
field_names = [field.name for field in fields(MyClass)]
resolved_field_types = {name: resolved_hints[name] for name in field_names}
推荐阅读
- python - ItemChanged 信号在 QTreeWidget 中触发 3 次
- ruby-on-rails - 如何知道在处理单个记录时是否进行了“包含”调用?
- string - 你能转换未来吗
到一个字符串?颤振/飞镖 - azure-web-app-service - 具有 VNET 集成的应用服务无法连接到同一 VNET 中的 HTTP 终结点
- java - Apache Ignite - 使用 Affinity Key 读取所有键、值
- database - 如何:具有大型数据库和快速访问一小部分数据的 Spring Boot 应用程序
- oracle - 如何在 Oracle Business Intelligence 11.1.1.9.0 (OBIEE) 的列级别添加切换按钮
- python - 如何解决 HTTP 错误 429:请求过多?
- ios - (SIGABRT 尝试使用未知类项目名称)Xcode 11、Swift 5、iOS 13 中强引用变量上的 EXC_BAD_ACCESS 错误
- laravel - Laravel - 无法使用用户名在 SMTP 服务器上进行身份验证