Python 3.7+dataclassesterm
__post_init__
initialization
The __post_init__ method is called automatically after __init__, for extra validation or processing.
Syntax
def __post_init__(self): ...
It is called only by the __init__ that the dataclass itself generated: with init=False, or with a hand-written __init__, nothing invokes it. Under frozen=True a plain self.x = ... raises FrozenInstanceError there, so you have to write object.__setattr__(self, "x", ...). InitVar fields land here too — they never become attributes, they are passed to __post_init__ as arguments, which is the sanctioned way to feed in data needed only during construction.
Examples
from dataclasses import dataclass
@dataclass
class Circle:
radius: float
def __post_init__(self):
if self.radius < 0:
raise ValueError('radius < 0')
self.area = 3.14 * self.radius ** 2
c = Circle(3.0)
c.area # → 28.26
# Circle(-1) # → ValueError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy