Validate with __post_init__
Beginner · Write the code · from Advanced Dataclasses: __post_init__, frozen, field(), slots, and Inheritance
From the lesson: Advanced Dataclasses: __post_init__, frozen, field(), slots, and Inheritance
You already know the basics of dataclasses - how to define fields, get automatic __init__ and __repr__, and set default values. Now it's time to unlock the advanced features.
Read the lessonCreate a dataclass called Age with one field: years (int). Add a __post_init__ method that raises a ValueError with the message 'Age must be positive' if years is less than 0. Create an Age(25) and print it. Then use try/except to catch the error from Age(-5) and print 'Invalid age'.
from dataclasses import dataclass
# Create the Age dataclass with validation
# Test valid and invalid ages
More Advanced Dataclass exercises
- Safe List Default with field()Beginner
- Predict the Output: Frozen DataclassIntermediate
- Computed Field with __post_init__Intermediate
- Dataclass InheritanceAdvanced
- Refactor: Add Validation and Computed FieldsAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz