首页 > 解决方案 > 如何获得 Python 3.7 新的数据类字段类型?

问题描述

Python 3.7 引入了称为数据类的新功能。

from dataclasses import dataclass

@dataclass
class MyClass:
    id: int = 0
    name: str = ''

在函数参数中使用类型提示(注解)时,您可以使用检查模块轻松获取注解类型。如何获取数据类字段类型?

标签: pythonpython-dataclasses

解决方案


检查__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}

推荐阅读