Editor

Fix the Bug: Validation Order

Advanced · Fix the bug · 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

This UserProfile class has a bug in its validation logic. The type coercion happens *after* the range check, so string inputs cause a TypeError instead of being validated properly. Fix the order of operations in __post_init__.

The code should print the profile when given age="25".

from dataclasses import dataclass
@dataclass
class UserProfile:
username: str
age: int
score: float
def __post_init__(self):
# Bug: validation before coercion!
if self.age < 0 or self.age > 150:
raise ValueError(f'Invalid age: {self.age}')
if self.score < 0 or self.score > 100:
raise ValueError(f'Invalid score: {self.score}')
self.age = int(self.age)
self.score = float(self.score)
self.username = str(self.username).strip().lower()
profile = UserProfile(username=' Alice ', age='25', score='99.5')
print(f'{profile.username}: age={profile.age}, score={profile.score}')

More Pydantic exercises

All Python exercises · 50 practice problems · Advanced Python quiz