Advertisement
Advanced Python, Dataclasses & NamedTuples

How do you add validation logic to a dataclass field using __post_init__?

Short answer

__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.

Save Python mock interview
Advertisement
AModel answer
__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.
Likely follow-ups
  • How would you compute a DERIVED field (not passed to __init__ directly) inside __post_init__?
Related topics