logo

Creating Models with BaseModel

The BaseModel class is where Pydantic starts. You define fields with type annotations, and Pydantic handles validation.

from pydantic import BaseModel

class Product(BaseModel):
    name: str
    price: float
    in_stock: bool

Create instances by passing keyword arguments or a dictionary:

# Keyword arguments
product = Product(name="Widget", price=9.99, in_stock=True)

# From dictionary
data = {"name": "Widget", "price": 9.99, "in_stock": True}
product = Product(**data)

Access fields like regular attributes:

print(product.name)   # Widget
print(product.price)  # 9.99

Pydantic models are like dataclasses with validation superpowers. You get type checking, serialization, and helpful error messages.

Learn BaseModel patterns in my Pydantic course.