Search code examples
pythonpython-typingpython-dataclasses

How to add a dataclass field without annotating the type?


When there is a field in a dataclass for which the type can be anything, how can you omit the annotation?

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

It seems the code above doesn't actually create a field for fav_duck. It just makes that a plain old class attribute.

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

Solution

  • 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'