Editor

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 lesson

Build 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.

from dataclasses import dataclass, asdict, fields
# Create ValidatedModel base class
# with to_dict() and from_dict() methods
# Create Book subclass with validation
# Create a book, print to_dict, reconstruct, print title

More Pydantic exercises

All Python exercises · 50 practice problems · Advanced Python quiz