How do I create dataclasses in Python with optional fields?
How does a dataclass work?
Dataclasses generate dunder methods on the user’s behalf. Instead of defining __init__
, __eq__
, etc. manually, these methods are provided out of the box simply be defining fields and their respestive types.
|
|
Because the methods and constructor are generated, the attributes are checked and hardcoded.
Optional fields in dataclasses
There are options for making an argument optional with dataclasses.
Using Optional[str]
and a default value
It is possible to make an optional argument by using a default value for the attribute.
|
|
Using InitVar
InitVar
is passed to the __init__
and __post_init__
methods, but is not stored as a class attribute. This can be valuable for some use-cases.
If a movie is not published, mark it as hidden.
|
|