Python › Dataclasses & NamedTuples
How do you add validation logic to a dataclass field using __post_init__?
AdvancedAnswer
__post_init__ is automatically called by the auto-generated __init__ RIGHT AFTER all fields are assigned, letting you add custom validation or derived-field computation without having to write __init__ manually from scratch.
@dataclass
class User:
name: str
age: int
def __post_init__(self):
if self.age < 0:
raise ValueError("Age cannot be negative")
# User("Sam", -5) # raises ValueError, caught by __post_init__Real-world example Validating that a dataclass's fields satisfy business rules (like a non-negative age or a valid email format) right after construction.