Challenge - 5 Problems
Pydantic Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the output of this Pydantic model validation?
Given the Pydantic model and input data below, what will be the value of
user.age after validation?FastAPI
from pydantic import BaseModel, Field class User(BaseModel): name: str age: int = Field(default=18, ge=0, le=120) user = User(name='Alice', age=25)
Attempts:
2 left
💡 Hint
Check the value passed to the model and the default value.
✗ Incorrect
The age field has a default of 18 but since 25 is provided and it meets the constraints (between 0 and 120), the value is set to 25.
📝 Syntax
intermediate2:00remaining
Which option correctly defines a Pydantic model with an optional email field?
Select the code snippet that correctly defines a Pydantic model with an optional
email field of type str.Attempts:
2 left
💡 Hint
Use the correct typing for optional fields and default values.
✗ Incorrect
Option C correctly imports Optional and sets the default to None. Option C uses valid syntax in Python 3.10+ but lacks a default value, making the field required. Options A and D misuse Optional.
🔧 Debug
advanced2:00remaining
What error does this Pydantic model raise when instantiated?
Consider this model and instantiation code. What error will occur?
FastAPI
from pydantic import BaseModel class Product(BaseModel): id: int price: float product = Product(id='abc', price=19.99)
Attempts:
2 left
💡 Hint
Check the type of the
id field and the value passed.✗ Incorrect
The id field expects an integer but a string 'abc' is provided. Pydantic raises a ValidationError listing the type mismatch.
❓ state_output
advanced2:00remaining
What is the output of this Pydantic model with a computed property?
Given the model below, what will
item.total_price output?FastAPI
from pydantic import BaseModel class Item(BaseModel): name: str quantity: int price_per_unit: float @property def total_price(self) -> float: return self.quantity * self.price_per_unit item = Item(name='Pen', quantity=3, price_per_unit=1.5) print(item.total_price)
Attempts:
2 left
💡 Hint
Multiply quantity by price_per_unit.
✗ Incorrect
The total_price property multiplies quantity (3) by price_per_unit (1.5), resulting in 4.5.
🧠 Conceptual
expert3:00remaining
Which option best describes Pydantic's model validation behavior on nested models?
Consider a Pydantic model with a nested model field. Which statement is true about how Pydantic validates nested models?
Attempts:
2 left
💡 Hint
Think about how Pydantic handles complex data structures.
✗ Incorrect
Pydantic automatically validates nested models recursively. Each nested model's fields are validated according to their definitions without extra manual steps.