如何获得 Python 3.7 新的数据类字段类型?
How can I get Python 3.7 new dataclass field types?
Python 3.7 引入了称为数据的新功能 类。
from dataclasses import dataclass
@dataclass
class MyClass:
id: int = 0
name: str = ''
在函数参数中使用类型提示(注释)时,您可以使用 inspect 模块轻松获得注释类型。如何获取数据类字段类型?
from dataclasses import dataclass
@dataclass
class MyClass:
id: int = 0
name: str = ''
myclass = MyClass()
myclass.__annotations__
>> {'id': int, 'name': str}
myclass.__dataclass_fields__
>> {'id': Field(name='id',type=<class 'int'>,default=0,default_factory=<dataclasses._MISSING_TYPE object at 0x0000000004EED668>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD),
'name': Field(name='name',type=<class 'str'>,default='',default_factory=<dataclasses._MISSING_TYPE object at 0x0000000004EED668>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD)}
在旁注中还有:
myclass.__dataclass_params__
>>_DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)
dataclasses.py is the module which provides decorator and functions for generating regular class methods by using of the field annotations. Which means that after processing class, the user defined fields shall be formed using PEP 526 Syntax of Variable annotations。模块注释可访问为 __annotations__
.
根据Runtime effects of type annotations the annotated types is accessible via __annotations__
attribute or by usage of the typing.get_type_hints,推荐最后一个。
请参阅下面的一些代码示例:
from typing import Dict, ClassVar, get_type_hints
from dataclasses import dataclass
@dataclass
class Starship:
hitpoints: int = 50
get_type_hints(Starship) // {'hitpoints': int}
Starship.__annotations__ // {'hitpoints': int}
dataclasses.__annotations__ // The annotations of the dataclasses module.
get_type_hints(get_type_hints)
检查 __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 3.7 引入了称为数据的新功能 类。
from dataclasses import dataclass
@dataclass
class MyClass:
id: int = 0
name: str = ''
在函数参数中使用类型提示(注释)时,您可以使用 inspect 模块轻松获得注释类型。如何获取数据类字段类型?
from dataclasses import dataclass
@dataclass
class MyClass:
id: int = 0
name: str = ''
myclass = MyClass()
myclass.__annotations__
>> {'id': int, 'name': str}
myclass.__dataclass_fields__
>> {'id': Field(name='id',type=<class 'int'>,default=0,default_factory=<dataclasses._MISSING_TYPE object at 0x0000000004EED668>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD),
'name': Field(name='name',type=<class 'str'>,default='',default_factory=<dataclasses._MISSING_TYPE object at 0x0000000004EED668>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD)}
在旁注中还有:
myclass.__dataclass_params__
>>_DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)
dataclasses.py is the module which provides decorator and functions for generating regular class methods by using of the field annotations. Which means that after processing class, the user defined fields shall be formed using PEP 526 Syntax of Variable annotations。模块注释可访问为 __annotations__
.
根据Runtime effects of type annotations the annotated types is accessible via __annotations__
attribute or by usage of the typing.get_type_hints,推荐最后一个。
请参阅下面的一些代码示例:
from typing import Dict, ClassVar, get_type_hints
from dataclasses import dataclass
@dataclass
class Starship:
hitpoints: int = 50
get_type_hints(Starship) // {'hitpoints': int}
Starship.__annotations__ // {'hitpoints': int}
dataclasses.__annotations__ // The annotations of the dataclasses module.
get_type_hints(get_type_hints)
检查 __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}