Sub topic 6
Validation and derived values with __post_init__
This chapter assumes you can write a basic @dataclass, declare fields with defaults, and use field(). It also assumes you know that __init__ is the method Python calls to set up a new object.
Why the generated `__init__` is not enough
The generated __init__ only assigns arguments to attributes. It does not check them, and it cannot compute one field from others. A dataclass handles this with a hook named __post_init__. If you define it, the generated __init__ calls it as its last step.
If __post_init__ raises an exception, no instance is returned. Invalid objects cannot be created.
Validating inputs
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 non-negative")
self.area = self.width * self.height
print(Rectangle(3, 4)) # Rectangle(width=3, height=4, area=12)
try:
Rectangle(-1, 4)
except ValueError as err:
print(err) # width and height must be non-negativeThe area field uses init=False. It is not a constructor parameter, so callers cannot pass it. The generated __init__ skips it, and __post_init__ sets it. It still appears in repr and in comparisons, because those options default to True.
Normalizing values
__post_init__ can also clean up values. This is useful when the same data can arrive in several shapes.
from dataclasses import dataclass
@dataclass
class Account:
email: str
tags: list[str]
def __post_init__(self):
self.email = self.email.strip().lower()
self.tags = sorted(set(self.tags))
acct = Account(" [email protected] ", ["b", "a", "b"])
print(acct) # Account(email='[email protected]', tags=['a', 'b'])Here __post_init__ replaces the attributes that __init__ just stored.
Frozen dataclasses need a workaround
A frozen dataclass blocks normal attribute assignment, and that includes assignments inside __post_init__. To set a derived field, bypass the block with object.__setattr__.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Circle:
radius: float
diameter: float = field(init=False)
def __post_init__(self):
if self.radius <= 0:
raise ValueError("radius must be positive")
object.__setattr__(self, "diameter", self.radius * 2)
print(Circle(2.5)) # Circle(radius=2.5, diameter=5.0)Common errors
- Stale derived values.
__post_init__runs once. If you later changewidth,areakeeps its old value. Either make the class frozen, or compute the value in a@propertyinstead. - Forgetting the parent hook. A subclass that defines its own
__post_init__replaces the parent's. Callsuper().__post_init__()if the parent has validation you still want. - Missing assignment. A field with
init=Falseand no default is never set by__init__. If__post_init__forgets it, the firstreprraisesAttributeError. - Validation that depends on field order. All fields are already assigned when
__post_init__runs. You can check relationships between fields, such asstart <= end, without worrying about which was set first.
Here is the stale-value problem in practice:
from dataclasses import dataclass, field
@dataclass
class Box:
side: float
volume: float = field(init=False)
def __post_init__(self):
self.volume = self.side ** 3
b = Box(2)
b.side = 3
print(b.volume) # 8, not 27When to use it
| Need | Tool |
|---|---|
| Reject bad input at creation | `__post_init__` raising an exception |
| Clean up or convert input | `__post_init__` reassigning fields |
| Value computed once from other fields | `field(init=False)` set in `__post_init__` |
| Value that must always match current fields | `@property` |
The next chapter covers InitVar. It lets __post_init__ receive an argument that is never stored on the instance.
Exercise
A dataclass Temperature has a field celsius: float and a field fahrenheit: float = field(init=False), set in __post_init__. After creating t = Temperature(100), you run t.celsius = 0. What does t.fahrenheit return, and how would you change the design so it stays correct?
Show answer
It still returns 212.0, because __post_init__ ran only once during construction. To keep the value correct, remove the fahrenheit field and define a @property named fahrenheit that returns self.celsius * 9 / 5 + 32. Alternatively, make the class frozen=True so celsius cannot change after creation.