CKTIS / Python
dataclass.__post_init__
The post-initialization hook computes dependent fields after the generated initializer assigns inputs.
Version: Python 3.14; repository image, production runtime not attested
Syntax
def __post_init__(self, multiplier): ...The post-initialization hook computes dependent fields after the generated initializer assigns inputs.
dataclass.__post_init__
This catalog label is not an attribute on the dataclass decorator function. The generated __init__ calls self.__post_init__ with InitVar values in declaration order. A custom initializer must make the call explicitly if needed.
multiplier is an init-only argument. With 6 and 4 the stored total is 24.
from dataclasses import dataclass
events=[]
@dataclass
class Custom:
def __init__(self): events.append('own')
def __post_init__(self): events.append('post')
Custom()
assert events==['own']
Examples
from dataclasses import InitVar, dataclass, field
@dataclass
class Price:
cents: int
multiplier: InitVar[int]
total: int = field(init=False)
def __post_init__(self, multiplier):
if multiplier < 0:
raise ValueError("negative")
self.total = self.cents * multiplier
p = Price(6, 4)
print(p.total, hasattr(p, "multiplier"))
Result
24 False
multiplier is an init-only argument. With 6 and 4 the stored total is 24.