How to add a dataclass field without annotating the type?
The dataclass decorator examines the class to find fields, by looking for names in __annotations__
. It is the presence of annotation which makes the field, so, you do need an annotation.
You can, however, use a generic one:
@dataclass
class Favs:
fav_number: int = 80085
fav_duck: 'typing.Any' = object()
fav_word: str = 'potato'
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.