Python __post_init__: Customizing Dataclass Initialization
How __post_init__ works in Python dataclasses: validation, derived fields, InitVar, inheritance, frozen instances, and common pitfalls.

Python's dataclasses module provides a concise way to define classes that primarily store data. The __post_init__ method, defined inside a dataclass, is invoked by the generated __init__ method after the fields have been assigned. This hook lets you add validation, compute derived fields, or perform any setup that depends on the already-initialized attributes. Understanding __post_init__ is essential when you need more control than a simple attribute assignment but still want to keep the dataclass ergonomics.
The Role of post_init in Dataclasses
When you decorate a class with @dataclass, Python generates an __init__ method that assigns each field to an instance attribute. After that assignment, if the class defines a method named __post_init__, the generated __init__ calls it as the final step. This happens automatically—you do not need to invoke it manually.
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
def __post_init__(self):
print(f"Point initialized at ({self.x}, {self.y})")
p = Point(1.0, 2.0)
# Output: Point initialized at (1.0, 2.0)The method runs after all fields are set, so you can safely read self.x and self.y. This is the primary use case: performing additional logic that requires the complete set of initialized attributes.
Adding Validation Logic
A common use of __post_init__ is to validate field values before the object is used. Because the method runs after assignment, you can raise exceptions early, preventing invalid objects from existing.
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
def __post_init__(self):
if self.age < 0:
raise ValueError("age cannot be negative")
if not self.name.strip():
raise ValueError("name cannot be empty")This keeps validation logic in one place and avoids duplicating checks in every place a Person might be constructed. It also works with default values and field(default_factory=...) because the method sees the final values.
Computing Derived Fields
Another frequent use is to compute fields that depend on other fields. For example, you might want to store a normalized version of an input or a cached property.
from dataclasses import dataclass
@dataclass
class Rectangle:
width: float
height: float
area: float = 0.0
def __post_init__(self):
self.area = self.width * self.heightHere area has a default, so callers do not need to pass it; __post_init__ computes it from width and height. This pattern is useful when you want to expose a derived value as a regular attribute rather than a property.
Using InitVar for Temporary Inputs
Sometimes you need a value during initialization that should not be stored as a field. The InitVar type from dataclasses lets you declare such parameters. __post_init__ receives them as arguments.
from dataclasses import dataclass, InitVar
from typing import Optional
@dataclass
class Circle:
radius: float = 0.0
diameter: InitVar[Optional[float]] = None
def __post_init__(self, diameter):
if diameter is not None:
self.radius = diameter / 2In this example, diameter is an InitVar. It is passed to __post_init__ as a parameter but is not stored as an attribute. This lets callers construct a Circle with Circle(diameter=4) without adding a diameter attribute to the instance.
Inheritance and Calling super().post_init
When a dataclass inherits from another dataclass, the generated subclass __init__ initializes fields from the base class as well as the subclass. It does not call the parent's __init__ separately. If both classes define __post_init__, the child's method overrides the parent's method, so the child must explicitly call super().__post_init__() to ensure the parent's logic runs.
from dataclasses import dataclass
@dataclass
class Base:
value: int
def __post_init__(self):
if self.value < 0:
raise ValueError("value must be non-negative")
@dataclass
class Child(Base):
name: str
def __post_init__(self):
super().__post_init__()
if not self.name:
raise ValueError("name cannot be empty")If you omit the super() call, the parent's validation is skipped. This is a common source of subtle bugs in inheritance hierarchies.
Frozen Dataclasses and Object.setattr
Frozen dataclasses (@dataclass(frozen=True)) make instances immutable. The generated __init__ uses object.__setattr__ to assign fields. Inside __post_init__, you cannot use normal attribute assignment (self.attr = value) because the instance is frozen. Instead, you must use object.__setattr__.
from dataclasses import dataclass
@dataclass(frozen=True)
class FrozenPoint:
x: float
y: float
norm: float = 0.0
def __post_init__(self):
object.__setattr__(self, 'norm', (self.x**2 + self.y**2)**0.5)Forgetting this raises FrozenInstanceError. This is a key difference between frozen and regular dataclasses when using __post_init__.
Performance and Runtime Considerations
__post_init__ runs on every instance creation. If the method performs heavy computation, it adds to the construction cost. For most use cases—validation or simple derived fields—the overhead is negligible. However, if you are creating many objects in a hot path, consider whether the logic can be deferred to a property or a lazy cache instead.
from dataclasses import dataclass
@dataclass
class Data:
values: list
def __post_init__(self):
self.sorted_values = sorted(self.values)This sorts on every construction. If the list is large and you create many instances, the cost may be significant. In such cases, a @property that sorts on access might be more appropriate, especially if not every instance's sorted values are needed.
Common Mistakes and Edge Cases
One common mistake is defining __post_init__ without the correct signature when using InitVar. The method must accept the InitVar parameters in the same order as they are declared. Another is forgetting that __post_init__ is not called if you define a custom __init__ manually. If you replace the generated __init__, you are responsible for calling __post_init__ yourself.
For a mutable field, use field(default_factory=list) or another factory instead of a bare mutable default. __post_init__ runs after the factory has created a fresh object for that instance, but it cannot repair a shared default from the class body.
Also, be aware of other construction paths. For a normal dataclass, dataclasses.replace() builds a new object by calling the class's __init__, so __post_init__ is run for the replacement. Default unpickling, on the other hand, usually restores instance state without calling __init__, so __post_init__ is not run during unpickling. If you rely on the method for invariants, verify that every construction path you use actually triggers it.
Understanding these behaviors helps you use __post_init__ effectively without introducing hidden bugs. The method is a powerful tool for keeping initialization logic centralized, but it requires awareness of its execution context and constraints.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.