How can I validate a dataclass's fields without hiding construction errors?
Quick answer
Put the invariant check in the dataclass’s __post_init__ method and raise a specific exception, such as ValueError, when the fields violate the rule. With the generated dataclass __init__, Python calls __post_init__ during construction, making it a direct place to validate relationships between fields. [S1] Let the exception remain visible rather than catching and suppressing it at the call site.
The question, the details, the next step.
A practical checklist
Write the field-combination rule as a condition that can be checked.
Put the check in __post_init__ when using the generated initializer.
Raise a specific exception with a message naming the violated rule.
Test both valid construction and an invalid combination.
If defining a custom __init__, explicitly check where validation will occur.
A few more useful answers
Should I validate each field separately or validate the combination?
Use the check that expresses the actual invariant. A rule involving two fields, such as one needing to be greater than another, belongs in a condition that checks both values together.
Does __post_init__ run when I write my own __init__?
The automatic call described in the documentation applies when the dataclass-generated __init__ is used; it does not occur if the class has no generated __init__. [S1] With a custom initializer, arrange validation explicitly.
What should the test assert about an invalid record?
Assert the intended exception type. Match the message too if its wording is useful to callers or is part of the behavior your project wants to preserve.
Sources
References used for this guide.
- [S1] dataclasses — Data Classes (Python 3.15.2 documentation) docs.python.org · Checked
