Challenge - 5 Problems
Pydantic Model Master
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 class User(BaseModel): name: str age: int = 18 input_data = {'name': 'Alice'} user = User(**input_data) print(user.age)
Attempts:
2 left
💡 Hint
Check the default value assigned to the age field in the model.
✗ Incorrect
Since the input data does not provide an age, Pydantic uses the default value 18 defined in the model.
📝 Syntax
intermediate2:00remaining
Which option correctly defines a Pydantic model with an optional string field?
Select the code snippet that correctly defines a Pydantic model with an optional
nickname field of type string.Attempts:
2 left
💡 Hint
Use the typing module's Optional type and assign None as default.
✗ Incorrect
Option C correctly uses Optional[str] with a default of None, which is the recommended way to declare optional fields in Pydantic.
❓ state_output
advanced2:00remaining
What error does this Pydantic model raise on invalid input?
Given the model and input below, what error will be raised when creating the model instance?
FastAPI
from pydantic import BaseModel class Product(BaseModel): id: int price: float input_data = {'id': 'abc', 'price': 10.5} product = Product(**input_data)
Attempts:
2 left
💡 Hint
Check the type of the 'id' field and the input value provided.
✗ Incorrect
The 'id' field expects an int, but the input provides a string 'abc', causing Pydantic to raise a ValidationError.
🧠 Conceptual
advanced2:00remaining
How does Pydantic handle extra fields by default?
If you pass extra fields not defined in the Pydantic model, what happens by default?
Attempts:
2 left
💡 Hint
Think about Pydantic's strictness with unexpected data.
✗ Incorrect
By default, Pydantic raises a ValidationError if extra fields are present in the input data that are not defined in the model.
🔧 Debug
expert3:00remaining
Why does this Pydantic model fail to parse nested data correctly?
Examine the code below. Why does
Order fail to parse the nested Item data correctly?FastAPI
from pydantic import BaseModel class Item(BaseModel): name: str quantity: int class Order(BaseModel): item: Item input_data = {'item': {'name': 'Book', 'quantity': '3'}} order = Order(**input_data) print(order.item.quantity, type(order.item.quantity))
Attempts:
2 left
💡 Hint
Pydantic automatically converts compatible types during validation.
✗ Incorrect
Pydantic automatically converts the string '3' to integer 3 when validating the nested Item model, so no error occurs.