Build a Mini Validator Framework
Advanced · Write the code · from Python Pydantic: Validate Data Like a Pro
From the lesson: Python Pydantic: Validate Data Like a Pro
Every application deals with messy data. User forms with missing fields, API responses with wrong types, config files with invalid values. Data validation is the practice of checking that data matches your expectations before you use it.
Read the lessonBuild a ValidatedModel base class with a to_dict() method that returns a dictionary of all fields, and a from_dict(cls, data) classmethod that creates an instance from a dictionary.
Then create a Book class that inherits from ValidatedModel with fields title (str), pages (int), and rating (float). Validate in __post_init__ that pages > 0 and 0 <= rating <= 5.
Create a book from a dict, print its to_dict() output, and then reconstruct it with from_dict and print the title.
More Pydantic exercises
- Basic Validated ModelAdvanced
- Multiple Field ValidationAdvanced
- Predict the Output: Coercion BehaviorAdvanced
- Nested Validated ModelsAdvanced
- Fix the Bug: Validation OrderAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz