Python
__post_init__
Learn post-init logic with __post_init__.
The __post_init__ method
In a dataclass __init__ is auto-generated, but sometimes you need validation or computation after the instance is created. The __post_init__ method is called right after the constructor finishes.
Example: def __post_init__(self):\n if self.value < 0:\n raise ValueError("negative not allowed"). This method runs after the constructor fills the fields. If a negative value is given, the error is raised during instance creation. So you block invalid instances from the start.
Ideal for validation
__post_init__ is the ideal place for validation. Since it runs after the constructor fills all fields, it can reach every field. You check conditions like negative values, empty strings or wrong types and raise an error if needed.
Another use is computing derived fields. Example: in a Rectangle class, you can take w and h fields and compute the area field inside __post_init__. So when the instance is ready, area is also filled.
Exercise Add __post_init__ to the Positive class
Start with from dataclasses import dataclass. Define a Positive class with @dataclass; include the field value: int = 0. Add a method def __post_init__(self):; in the body write if self.value < 0: and raise ValueError("negative not allowed"). Then create an instance with p = Positive(5) and print with print(p.value).
Show example solution
# Add __post_init__ to the Positive class
from dataclasses import dataclass
@dataclass
class Positive:
value: int = 0
def __post_init__(self):
if self.value < 0:
raise ValueError("negative not allowed")
p = Positive(5)
print(p.value)
Test yourself
-
Match the __post_init__ parts
- __post_init__
- Post-constructor method
- __init__
- Auto constructor
- ValueError
- Validation error
- self.value
- Validated field
-
When does __post_init__ run?
- When the class is defined
- Right after the constructor
- Only on error
- When the instance is deleted
Show answer
Right after the constructor — __post_init__ runs right after the constructor finishes.
-
Complete the validation body
def __post_init__(self):
if self.value < 0:
raise ____("negative not allowed")
Show answer
def __post_init__(self):
if self.value < 0:
raise ValueError("negative not allowed")
Next lesson: asdict and astuple