Editor

Nested Validated Models

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

Create two dataclasses:

1. Item with name (str) and price (float). Validate that price >= 0.

2. Order with customer (str) and items (list). In __post_init__, convert any dicts in the items list to Item objects. Add a method total() that returns the sum of all item prices.

Create an order:

order = Order(
    customer='Alice',
    items=[{'name': 'Book', 'price': 12.99}, {'name': 'Pen', 'price': 1.50}]
)

Print the customer name and then the total.

from dataclasses import dataclass
# Create Item dataclass with price validation
# Create Order dataclass with dict-to-Item conversion
# and a total() method
# Create order and print results

More Pydantic exercises

All Python exercises · 50 practice problems · Advanced Python quiz