获取有关数据类字段的类型信息
Get type information about dataclass fields
对于给定的数据类,如何获取有关字段类型的信息?
示例:
>>> from dataclasses import dataclass, fields
>>> import typing
>>> @dataclass
... class Foo:
... bar: typing.List[int]
我可以通过 repr 获取字段信息:
>>> fields(Foo)
(Field(name='bar',type=typing.List[int],default=<dataclasses._MISSING_TYPE object at 0x7fef9aafd9b0>,default_factory=<dataclasses._MISSING_TYPE object at 0x7fef9aafd9b0>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD),)
我可以拥有我的栏字段的类型代表
>>> fields(Foo)[0].type
typing.List[int]
如何检索(作为 python 对象,而不是字符串 repr):
- 类型 (
typing.List
)
- type
typing.List
(int
) 中的项目类型
?
数据 class 字段的 type
属性 它不是字符串表示,它是一种类型。
Python 3.6:
>>> type(fields(Foo)[0].type)
<class 'typing.GenericMeta'>
Python 3.7:
>>> type(fields(Foo)[0].type)
<class 'typing._GenericAlias'>
在这种情况下,您可以使用 __args__
属性:
检索内部类型
>>> fields(Foo)[0].type.__args__
(<class 'int'>,)
对于给定的数据类,如何获取有关字段类型的信息?
示例:
>>> from dataclasses import dataclass, fields
>>> import typing
>>> @dataclass
... class Foo:
... bar: typing.List[int]
我可以通过 repr 获取字段信息:
>>> fields(Foo)
(Field(name='bar',type=typing.List[int],default=<dataclasses._MISSING_TYPE object at 0x7fef9aafd9b0>,default_factory=<dataclasses._MISSING_TYPE object at 0x7fef9aafd9b0>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD),)
我可以拥有我的栏字段的类型代表
>>> fields(Foo)[0].type
typing.List[int]
如何检索(作为 python 对象,而不是字符串 repr):
- 类型 (
typing.List
) - type
typing.List
(int
) 中的项目类型
?
type
属性 它不是字符串表示,它是一种类型。
Python 3.6:
>>> type(fields(Foo)[0].type)
<class 'typing.GenericMeta'>
Python 3.7:
>>> type(fields(Foo)[0].type)
<class 'typing._GenericAlias'>
在这种情况下,您可以使用 __args__
属性:
>>> fields(Foo)[0].type.__args__
(<class 'int'>,)