← Python lessons

Python Dataclass Validation with __post_init__

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

Python dataclass validation checks field values as each object is made. A method that runs after the generated constructor raises an error for a bad value.

Read Python Dataclasses, Raising exceptions and Try and except first. This lesson writes that method, __post_init__(), to check one field, and handles the objects it rejects. Every example imports dataclass from Python's standard dataclasses module, so nothing needs installing.

Validate after generated initialization

Add a method called __post_init__ that takes only self. Inside it, check a field and raise an exception when the value is not allowed.

from dataclasses import dataclass@dataclassclass Ticket:    event: str    price: int    def __post_init__(self):        if self.price < 0:            raise ValueError("price can't be negative")print(Ticket("Gig", 20))print(Ticket("Gig", -5))  # this line raises ValueError

This prints Ticket(event='Gig', price=20), then stops with ValueError: price can't be negative. The generated __init__() stored -5 in self.price and then ran __post_init__(). The raise stops the construction, so Ticket("Gig", -5) never gives you an object.

Put a check here when every object of the class must follow the rule. Then no code can make a bad Ticket by calling the class.

Do not confuse __post_init__() with __init__(). @dataclass writes __init__() for you, and it stores the fields. You write __post_init__(), but you never call it: the generated __init__() calls it last. If you write your own __init__() in a dataclass, it replaces the generated one. Then nothing stores the fields or calls __post_init__() for you.

Catch a rejected construction

The error comes out of the Ticket(...) call. To carry on after a bad value, put that call inside try and catch the ValueError.

from dataclasses import dataclass@dataclassclass Ticket:    event: str    price: int    def __post_init__(self):        if self.price < 0:            raise ValueError("price can't be negative")tickets = []for event, price in [("Gig", 20), ("Play", -5), ("Film", 8)]:    try:        tickets.append(Ticket(event, price))    except ValueError:        print("skipped", event)print(len(tickets), "tickets made")

This prints skipped Play, then 2 tickets made. The loop unpacks each pair into event and price. When Ticket(...) raises, append() never runs, so the list holds only the two good tickets.

Validation runs only when the object is made

__post_init__() runs once, inside the generated __init__(). Setting a field later does not run it again.

from dataclasses import dataclass@dataclassclass Ticket:    event: str    price: int    def __post_init__(self):        if self.price < 0:            raise ValueError("price can't be negative")ticket = Ticket("Gig", 20)ticket.price = -5print(ticket)

This prints Ticket(event='Gig', price=-5) with no error. The check guards creation only. If a field changes later, change it through a method that checks the new value as well.

Spell __post_init__ exactly

The generated __init__() looks for exactly this name: two underscores, post_init, two underscores. Any other name is an ordinary method that nothing calls.

from dataclasses import dataclass@dataclassclass Ticket:    event: str    price: int    def post_init(self):  # wrong name: the generated __init__() never calls it        if self.price < 0:            raise ValueError("price can't be negative")print(Ticket("Gig", -5))

This prints Ticket(event='Gig', price=-5). No error appears, so a misspelt name fails silently. If a bad value gets through, check the spelling first.

Note: These examples check one value of the right type. Type hints are still not checked, so Ticket("Gig", "20") fails inside __post_init__() with a TypeError from <, not your ValueError. Checking the types of outside data, such as a JSON file, is left out here.

See also: Data validation, Python Dataclass Methods.

Your turn

Give Badge a __post_init__() that raises a ValueError when code does not have exactly 3 characters. The loop then makes only the badges with a 3-character code.

🎯 Goal — make it print exactly:
rejected B2
rejected LONG
2 badges made
from dataclasses import dataclass@dataclassclass Badge:    owner: str    code: str    # add __post_init__(self): raise a ValueError when len(self.code) is not 3badges = []for code in ["AX7", "B2", "LONG", "Q9Z"]:    try:        badges.append(Badge("Bo", code))    except ValueError:        print("rejected", code)print(len(badges), "badges made")