Using __post_init__ in Python Dataclasses
Learn how to use __post_init__ in Python dataclasses to validate fields, compute derived values, and customize initialization behavior.

__post_init__ is a hook provided by Python's @dataclass decorator. When a dataclass generates its __init__, it assigns the declared fields and then, if the class defines __post_init__, calls that method automatically at the end of the generated initializer. Use it to validate values, normalize inputs, compute derived fields, or set up attributes that are not part of the constructor signature.
What post_init Does and When to Use It
__post_init__ is a method you define inside a dataclass. The @dataclass decorator generates an __init__ that, after assigning all fields, calls self.__post_init__() if it exists. This lets you run arbitrary code that depends on the initialized field values.
Use __post_init__ when you need to:
- Validate field values and raise exceptions early
- Compute derived fields from other fields
- Normalize or transform input values before storing them
- Set up attributes that are not part of the constructor signature
For example, consider a dataclass representing a rectangle. You might want to ensure that width and height are positive and also compute the area automatically:
from dataclasses import dataclass, field
@dataclass
class Rectangle:
width: float
height: float
area: float = field(init=False)
def __post_init__(self):
if self.width <= 0 or self.height <= 0:
raise ValueError('Width and height must be positive')
self.area = self.width * self.heightWithout __post_init__, you would have to override __init__ manually, which defeats the purpose of using dataclasses. The hook keeps the generated __init__ intact while adding custom behavior.
Validating Field Values in post_init
Validation is one of the most common uses of __post_init__. Since the method runs after all fields are assigned, you can check any combination of fields and raise an exception if the state is invalid.
Suppose you have a dataclass for a bank account. You want to ensure that the initial balance is not negative and that the account number has a specific format:
from dataclasses import dataclass
import re
@dataclass
class BankAccount:
account_number: str
balance: float = 0.0
def __post_init__(self):
if self.balance < 0:
raise ValueError('Initial balance cannot be negative')
if not re.fullmatch(r'\d{10}', self.account_number):
raise ValueError('Account number must be 10 digits')This validation runs on every normal construction, so you cannot create an invalid object through the generated __init__. That is a strong guarantee for code that relies on invariants. However, be aware that validation in __post_init__ does not protect against later mutation. If fields are mutable, consider making the dataclass frozen or adding validation at the points where values can change.
Computing Derived Fields
Another typical use is computing a field that depends on other fields. In the rectangle example above, area is derived from width and height. You can also compute fields that are not part of the constructor but are useful as attributes.
Consider a dataclass for a temperature reading. You might want to store Celsius and also provide Fahrenheit as a computed property. While a property works, you may prefer to store the computed value in a field for performance or serialization reasons:
from dataclasses import dataclass, field
@dataclass
class Temperature:
celsius: float
fahrenheit: float = field(init=False)
def __post_init__(self):
self.fahrenheit = self.celsius * 9 / 5 + 32Now fahrenheit is a regular field that can be serialized by tools like asdict() or dataclasses.astuple(). If you used a property instead, it would not appear in the dataclass fields and would not be included in generated methods like __eq__ or __repr__. The choice depends on whether you need the derived value to be part of the object's data or just a convenience accessor.
Using InitVar for Parameters Not Stored as Fields
Sometimes you need to pass extra arguments to __init__ that are not stored as fields. For example, you might want to accept a database connection or a configuration object that is used only during initialization. InitVar is a special type annotation that tells the dataclass to include the parameter in __init__ but not store it as an attribute.
from dataclasses import dataclass, InitVar
@dataclass
class User:
name: str
age: int
db: InitVar[object] = None
def __post_init__(self, db):
if db is not None:
db.insert_user(self.name, self.age)Here, db is passed to __init__ and then forwarded to __post_init__ as an argument. It is not stored as an attribute, so it does not affect equality, hashing, or representation. This pattern is useful for dependency injection or for performing side effects during object creation without polluting the object's state.
Interaction with Inheritance and Field Defaults
When you inherit from a dataclass, the generated __init__ includes fields from all base classes. If both the base and the subclass define __post_init__, the subclass's method overrides the base's method. To run both, you must call super().__post_init__() explicitly.
from dataclasses import dataclass
@dataclass
class Base:
x: int
def __post_init__(self):
if self.x < 0:
raise ValueError('x must be non-negative')
@dataclass
class Derived(Base):
y: int
def __post_init__(self):
super().__post_init__()
if self.y < 0:
raise ValueError('y must be non-negative')If you forget the super() call, the base validation is skipped. This is a common mistake, especially when the base class has important invariants. Also note that __post_init__ runs after all fields, including inherited ones, are assigned, so you can rely on the complete state.
Field defaults also interact with __post_init__. If a field has a default value and you assign it in __post_init__, the default is overwritten. That is fine, but be careful with mutable defaults. As with any dataclass, avoid using mutable default values directly; use field(default_factory=...) instead. In __post_init__, you can still modify mutable fields, but the same caution applies.
Performance and Maintainability Considerations
__post_init__ runs on every instance creation, so it adds a small overhead. For most applications, this is negligible, but if you are creating millions of objects in a tight loop, the extra method call and any logic inside it can become measurable. Keep the method as light as possible. If you need heavy processing, consider moving it to a separate factory function or a class method that constructs the object and then performs the work.
From a maintainability perspective, __post_init__ centralizes initialization logic. That is a benefit because it avoids duplicating checks across multiple constructors or factory methods. However, it can also become a dumping ground for unrelated code. Keep it focused on invariants and derived values. If you find yourself adding logging, sending notifications, or performing I/O inside __post_init__, reconsider whether that belongs in the object's lifecycle.
Another consideration is how copies interact with __post_init__. dataclasses.replace() creates a new instance using the generated __init__, so __post_init__ is called. copy.copy() and copy.deepcopy(), on the other hand, may bypass __init__ entirely, depending on the implementation. If your post-init logic is critical for the object's validity, be aware that copies might not trigger it. In practice, this is rarely an issue because copied objects already have valid field values, but it is worth knowing.
Common Mistakes and Edge Cases
One common mistake is forgetting to call super().__post_init__() in a subclass. Another is assuming that __post_init__ can access class-level defaults that were not assigned. For example, if a field is not provided and has a default, the default is assigned before __post_init__ runs, so it is available. That is usually what you want.
A subtle edge case involves fields that are excluded from __init__ using field(init=False). These fields are not set by the generated __init__, but they are still assigned their default value. In __post_init__, you can compute and assign them. This is a common pattern for derived fields that should not be part of the constructor signature:
from dataclasses import dataclass, field
@dataclass
class Circle:
radius: float
area: float = field(init=False)
def __post_init__(self):
self.area = 3.14159 * self.radius ** 2Here, area is not a parameter of __init__, but it is still a field and will appear in __repr__ and __eq__. This is a clean way to expose computed data without letting users set it directly.
Another edge case is using __post_init__ with frozen=True. In a frozen dataclass, fields are immutable after creation. If you try to assign a field normally inside __post_init__, you will get a FrozenInstanceError. To compute a derived field in a frozen dataclass, use object.__setattr__ to bypass the generated __setattr__ check:
from dataclasses import dataclass, field
@dataclass(frozen=True)
class FrozenPoint:
x: float
y: float
distance: float = field(init=False)
def __post_init__(self):
object.__setattr__(self, 'distance', (self.x ** 2 + self.y ** 2) ** 0.5)InitVar can be useful in frozen dataclasses when you need an extra constructor argument, but it does not remove the need for object.__setattr__ when the computed value becomes a stored field. If you want to avoid modifying fields in __post_init__, compute the value before constructing the object and pass it as an ordinary field, for example through a classmethod factory.
Finally, remember that __post_init__ is only called when the dataclass is instantiated normally. If you use dataclasses.make_dataclass or dynamically create classes, the same rules apply. The method is just a regular method, so you can also call it manually if you need to reinitialize an object, but that is rarely necessary.
Understanding __post_init__ is essential for writing robust dataclasses that enforce invariants and compute derived state cleanly. It is a small hook with significant power, and using it correctly keeps your initialization logic in one place.
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.