CodeBlanks Logo Icon CodeBlanks

BaseModel

Learn to define models with pydantic.BaseModel.

BaseModel

pydantic.BaseModel is the base class for data models. You derive a class, give types to fields; Pydantic validates the data and converts it automatically.

from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int

u = User(name="Ayşe", age=30)
print(u.name, u.age)  # Ayşe 30

Wrong types raise a Pydantic error. You can also build a model from a dict; a missing field still raises an error.

Fields and types

Each field is defined with a type: str, int, float, bool, list and so on. Pydantic tries to convert data to this type; if it cannot, it raises.

class User(BaseModel):
    name: str
    age: int
    active: bool

u = User(name="Ayşe", age="30", active=True)
print(u.age)  # 30 (converted to int)

This is useful when the data source is untrusted; for example, strings from a form are turned into integers automatically.

Practice Create a User model

Start with from pydantic import BaseModel. Define class User(BaseModel): with fields name: str and age: int. Create an instance with u = User(name="Ayşe", age=30). Print the values with print(u.name, u.age).

Starter code

main.py
# bring in BaseModel from pydantic
# define User class (derive from BaseModel, name and age fields)
# create a User instance (Ayşe, 30)
# print the name and age values

Sample solution

main.py
from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int

u = User(name="Ayşe", age=30)
print(u.name, u.age)

Expected output

Ayşe 30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if you omit a field in a model derived from BaseModel?

  • The field becomes None
  • An error is raised Correct answer
  • The field becomes an empty string
  • A warning is issued but it continues

Explanation: A missing required field raises a Pydantic error.

2 Complete the BaseModel derivation

Question
from pydantic import BaseModel

class User(____):
    name: str
    age: int
Answer
from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int

Explanation: class User(BaseModel) defines a model.

3 Match the BaseModel concepts

Term Meaning
BaseModel Is the base class
name: str Is a field definition
User(name=, age=) Creates an instance
u.name Is the field value

All lessons in Advanced