After learning a little about dataclasses, it seems that a dataclass will always HAVE all the properties you defined. Adding the Optional only means that you don't have to pass a param into the constructor. I want to make a field required in the sense that it cannot be None.
So if I have
@dataclass
class SomeClass():
a: int
b: Optional[int] = None
test = SomeClass(a=None)
I want this to throw an error, but don't know the best way to achieve that result.
Two ideas I have are using the __post_init__ to run validation logic or maybe using pydantic.
Is there a generally accepted solution for this problem?
Both ways you mentioned are quite suitable, but
pydantic.dataclasseswill do automatic validation for you:Gives a verbose output/error:
With standard
dataclassesyou'd need to provide your own validation logic within__post_init__method: