Establish Invariants in Post-Init
Core idea
An invariant is a condition a valid record must satisfy. The generated initializer calls post_init after assigning fields, making it a useful place for cross-field checks or derived values. field(init=False) excludes a field from the generated initializer. A custom initializer must explicitly arrange any post-initialization work.
from dataclasses import dataclass@dataclassclass Span: start:int end:int def __post_init__(self): if self.end < self.start: raise ValueError('inverted span')print(Span(2,5).end)try: Span(5,2)except ValueError as exc: print(exc)The invalid object fails construction because the end precedes the start.
Compute a derived field
from dataclasses import dataclass,field@dataclassclass Panel: width:int height:int area:int=field(init=False) def __post_init__(self): if min(self.width,self.height)<=0: raise ValueError('positive dimensions required') self.area=self.width*self.heightprint(Panel(3,4).area)Area is calculated from validated dimensions, not accepted from the caller.
Common mistake
Post-init runs at construction, not after every attribute assignment. A mutable derived field may become stale; use a property or control mutation when consistency is required.
Practice
Add a capacity invariant to a storage record and test zero, positive and over-capacity inputs. Decide how later mutation will be handled.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Post-init and validation
Check your understanding of post-init and validation.
What is printed?
from dataclasses import dataclass@dataclassclass A: n:int def __post_init__(self): self.n+=1print(A(2).n)What is printed?
from dataclasses import dataclass,field@dataclassclass A: n:int twice:int=field(init=False) def __post_init__(self): self.twice=2*self.na=A(3);a.n=4print(a.twice)When is __post_init__ called automatically?
What does init=False do on a field?