20

当数据类中有一个类型可以是任何类型的字段时,如何省略注释?

@dataclass
class Favs:
    fav_number: int = 80085
    fav_duck = object()
    fav_word: str = 'potato'

似乎上面的代码实际上并没有为fav_duck. 它只是使它成为一个普通的旧类属性。

>>> Favs()
Favs(fav_number=80085, fav_word='potato')
>>> print(*Favs.__dataclass_fields__)
fav_number fav_word
>>> Favs.fav_duck
<object at 0x7fffea519850>
4

2 回答 2

17

dataclass 装饰器检查类以查找字段,方法是在__annotations__. 正是注释的存在使得该字段,所以,你确实需要一个注释。

但是,您可以使用通用的:

@dataclass
class Favs:
    fav_number: int = 80085
    fav_duck: 'typing.Any' = object()
    fav_word: str = 'potato'
于 2018-05-12T22:43:27.333 回答
5

According to PEP 557 which defines the meaning of data classes,

The dataclass decorator examines the class to find fields. A field is defined as any variable identified in __annotations__. That is, a variable that has a type annotation.

Which is to say that the premise of this question (e.g. "How can I use dataclass with a field that has no type annotation) must be rejected. The term 'field' in the context of dataclass necessitates that the attribute has a type annotation by definition.

Note that using a generic type annotation like typing.Any is not the same as having an unannotated attribute, since the attribute will appear in __annotations__.

Finally, the helper function make_dataclass will automatically use typing.Any for the type annotation in cases when only an attribute name is supplied, and this is also mentioned in the PEP with an example.

于 2018-04-19T22:31:45.430 回答