Sub topic 6
Validation and derived values with __post_init__
This chapter assumes you can write a basic @dataclass, declare defaults, and use field(). You should also know the difference between mutable and immutable objects. The examples need Python 3.7 or newer.
Where __post_init__ fits
The @dataclass decorator generates an __init__ that assigns each field in declaration order. If the class defines a method named __post_init__, the generated __init__ calls it as its last step, with no arguments beyond self. By then every field has a value, so the method can check the values, normalize them, or compute other fields from them.
Two consequences follow from this order:
__post_init__sees all fields, including ones that came fromdefault_factory.- If it raises, the caller gets the exception and never receives a half-built object.
Validating inputs
The most common use is rejecting bad values at construction time.
from dataclasses import dataclass
@dataclass
class Account:
owner: str
balance: float = 0.0
def __post_init__(self):
if not self.owner.strip():
raise ValueError("owner must not be empty")
if self.balance < 0:
raise ValueError(f"balance must be >= 0, got {self.balance}")
print(Account("Ana", 10))
try:
Account("Ben", -5)
except ValueError as exc:
print(exc)This prints Account(owner='Ana', balance=10) and then balance must be >= 0, got -5.
Raise ValueError when the type is right but the value is not. Raise TypeError when the type itself is wrong. Put the offending value in the message, because the traceback points at __init__, not at the caller's mistake.
Annotations are not checked
A dataclass does not enforce its type annotations. Account("Ana", "ten") builds successfully, and the first comparison with a number fails later and far from the cause. If you need type safety at construction, check it yourself in __post_init__ or use a validation library.
Normalizing and coercing values
__post_init__ can also rewrite fields. This is useful when callers may pass the same information in several forms, such as ISO date strings or mixed-case text.
from dataclasses import dataclass, field
from datetime import date
@dataclass
class Booking:
guest: str
start: date
end: date
nights: int = field(init=False)
def __post_init__(self):
if isinstance(self.start, str):
self.start = date.fromisoformat(self.start)
if isinstance(self.end, str):
self.end = date.fromisoformat(self.end)
if self.end < self.start:
raise ValueError("end must not be before start")
self.guest = self.guest.strip().title()
self.nights = (self.end - self.start).days
b = Booking(" ana ", "2026-12-01", date(2026, 12, 5))
print(b.guest, b.nights) # Ana 4The caller passed one string date and one date object, and both end up as date values. The method does the work in a fixed order: convert, check, then derive. Doing the checks after the conversions means they compare like with like.
Derived fields with init=False
A derived field is computed from other fields, so the caller should not supply it. Declare it with field(init=False). Then it does not appear in the generated __init__ signature, and __post_init__ assigns it.
from dataclasses import dataclass, field
@dataclass
class Rectangle:
width: float
height: float
area: float = field(init=False)
def __post_init__(self):
if self.width < 0 or self.height < 0:
raise ValueError("width and height must be non-negative")
self.area = self.width * self.height
r = Rectangle(3, 4)
print(r) # Rectangle(width=3, height=4, area=12)Three details matter here.
- A field with
init=Falseand no default is not set by__init__. If__post_init__forgets to assign it, thenprint(r)raisesAttributeError, because the generated__repr__reads every field. - A field without a default may follow fields with defaults only if
init=False. The ordering rule applies to parameters of__init__, and this field is not one. - The derived field still takes part in
__eq__and__repr__. Passcompare=Falseorrepr=Falsetofield()if you want it left out.
The stale value problem
__post_init__ runs once. If someone changes width later, area is not recomputed.
r = Rectangle(3, 4)
r.width = 10
print(r.area) # 12, but the real area is now 40You have three ways to handle this:
- Make the class immutable with
frozen=True, so the fields cannot change. This is covered below and in a later chapter. - Replace the stored field with a read-only property, so the value is always computed on demand.
- Treat instances as values and build a new one with
replace().
The property version looks like this:
from dataclasses import dataclass
@dataclass
class Rectangle:
width: float
height: float
@property
def area(self):
return self.width * self.height
r = Rectangle(3, 4)
r.width = 10
print(r.area) # 40A property cannot go stale, but it recomputes on every access and it does not show up in repr or asdict. Store the value when the computation is expensive and the inputs do not change. Use a property when the computation is cheap or the inputs may change.
Validation does not cover later changes
Checks in __post_init__ guard construction only. After that, ordinary attribute assignment skips them.
a = Account("Ana", 10)
a.balance = -999 # no error, the invariant is now brokenIf an invariant must hold for the whole life of the object, choose one of these:
- Use
frozen=True, so values are fixed after validation. - Define
__setattr__or a property for the guarded field and validate there. - Keep changes behind methods such as
withdraw()that check before they assign.
Using __post_init__ with frozen=True
A frozen dataclass blocks self.attr = value, and that includes assignments inside __post_init__. To set a derived field you have to bypass the block with object.__setattr__.
import math
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Circle:
radius: float
area: float = field(init=False)
def __post_init__(self):
if self.radius <= 0:
raise ValueError("radius must be positive")
object.__setattr__(self, "area", math.pi * self.radius ** 2)
c = Circle(2)
print(round(c.area, 2)) # 12.57Because the instance is frozen, the derived area can never go stale. This is the usual reason to combine the two features.
Inheritance: call super().__post_init__()
A subclass that defines its own __post_init__ replaces the parent's version. Python does not chain them for you. Forgetting the call silently drops the parent's validation.
from dataclasses import dataclass
@dataclass
class Item:
name: str
price: float
def __post_init__(self):
if self.price < 0:
raise ValueError("price must be non-negative")
@dataclass
class Perishable(Item):
days_left: int = 7
def __post_init__(self):
super().__post_init__()
if self.days_left < 0:
raise ValueError("days_left must be non-negative")
print(Perishable("milk", 1.2))
try:
Perishable("milk", -1.0)
except ValueError as exc:
print(exc) # price must be non-negativeIf the subclass does not define __post_init__ at all, the parent's version is inherited and runs as expected.
Interaction with replace()
dataclasses.replace(obj, **changes) creates a new instance by calling the class again, so __post_init__ runs again. This gives you validation and recomputation for free.
from dataclasses import dataclass, field, replace
@dataclass
class Rectangle:
width: float
height: float
area: float = field(init=False)
def __post_init__(self):
if self.width < 0 or self.height < 0:
raise ValueError("width and height must be non-negative")
self.area = self.width * self.height
r = Rectangle(3, 4)
print(replace(r, width=5).area) # 20
for changes in ({"width": -1}, {"area": 1}):
try:
replace(r, **changes)
except ValueError:
print("rejected", changes)The first call recomputes area as 20. The loop prints a line for both changes. The first is rejected by your validation, and the second is rejected by replace() itself, because you cannot pass a value for a field declared with init=False.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Defining your own `__init__` or using `@dataclass(init=False)` | `__post_init__` never runs | Let the decorator generate `__init__` |
| Forgetting to assign an `init=False` field | `AttributeError` on `repr` or comparison | Assign it on every path through `__post_init__`, or give it a default |
| Assigning to a field of a frozen class | `FrozenInstanceError` | Use `object.__setattr__` inside `__post_init__` |
| Overriding without `super().__post_init__()` | Parent checks are skipped | Call the parent version first |
| Expecting validation after construction | Bad values get in later | Freeze the class or guard assignment |
Choosing what belongs here
Keep __post_init__ short and free of side effects. Checks, coercions, and cheap derived values fit well. Network calls, file reads, and heavy computation do not, because every replace() and every copy pays for them again. A classmethod such as Booking.from_json(...) is a better place for work that depends on outside data.
When the constructor needs a value that should not be stored, such as a plain-text password that becomes a hash, the next chapter's InitVar passes it to __post_init__ without making it a field.
Exercise
A frozen dataclass Temperature has a field celsius: float and a derived field fahrenheit: float = field(init=False). Write the __post_init__ that rejects values below -273.15 and sets fahrenheit. Then say what happens if you write self.fahrenheit = ... instead of your approach.
Show answer
Use if self.celsius < -273.15: raise ValueError("below absolute zero") and then object.__setattr__(self, "fahrenheit", self.celsius * 9 / 5 + 32). The plain assignment self.fahrenheit = ... raises FrozenInstanceError because the class is frozen, so every attempt to create a Temperature fails inside __post_init__.
Exercise
Dog subclasses a dataclass Animal whose __post_init__ rejects an empty name. Dog defines its own __post_init__ that checks age >= 0 and does not call super(). Does Dog("", 3) raise an error? Why, and how do you fix it?
Show answer
No error is raised. The Dog method replaces the Animal method, so the empty-name check never runs. Add super().__post_init__() at the start of the Dog method.