Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python __post_init__: Customizing Dataclass Initialization

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

~4 min readPython
#dataclasses#initialization#validation#derived fields
Illustration of a Python dataclass with a __post_init__ method that validates and computes derived fields after initialization.

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.

python
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.

python
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.

python
from dataclasses import dataclass @dataclass class Rectangle: width: float height: float area: float = 0.0 def __post_init__(self): self.area = self.width * self.height

Here 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.

python
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 / 2

In 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.

python
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__.

python
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.

python
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 tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.