Basic Validated Model
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 lessonCreate a Temperature dataclass with a single field celsius (float). In __post_init__, coerce celsius to float and validate that it's above absolute zero (-273.15). If invalid, raise ValueError.
Create two instances: Temperature(celsius='100') and Temperature(celsius=-10). Print each one's celsius value.
from dataclasses import dataclass
# Create the Temperature dataclass with validation
# Create instances and print their celsius values
More Pydantic exercises
- Multiple Field ValidationAdvanced
- Predict the Output: Coercion BehaviorAdvanced
- Nested Validated ModelsAdvanced
- Fix the Bug: Validation OrderAdvanced
- Build a Mini Validator FrameworkAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz