🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Data Models and Validation

Python DatađŸŸĸ Free Lesson

Advertisement

Data Models and Validation

Pydantic, dataclasses, and data validation patterns.

Overview

Master data modeling patterns.

Dataclasses

python
from dataclasses import dataclass, field
from typing import List

@dataclass
class User:
    name: str
    email: str
    age: int
    hobbies: List[str] = field(default_factory=list)
    
    def greet(self):
        return f"Hello, {self.name}!"

user = User("Alice", "[email protected]", 25, ["reading", "coding"])
print(user.greet())

Pydantic Models

python
from pydantic import BaseModel, EmailStr, validator
from typing import Optional

class User(BaseModel):
    name: str
    email: EmailStr
    age: int
    bio: Optional[str] = None
    
    @validator('age')
    def age_must_be_positive(cls, v):
        if v < 0:
            raise ValueError('Age must be positive')
        return v
    
    @validator('name')
    def name_must_not_be_empty(cls, v):
        if not v.strip():
            raise ValueError('Name cannot be empty')
        return v.strip()

# Usage
user = User(name="Alice", email="[email protected]", age=25)
print(user.dict())

Validation Patterns

python
from pydantic import BaseModel, validator
from typing import List

class Order(BaseModel):
    items: List[str]
    total: float
    
    @validator('total')
    def total_must_be_positive(cls, v):
        if v <= 0:
            raise ValueError('Total must be positive')
        return round(v, 2)
    
    @validator('items')
    def items_cannot_be_empty(cls, v):
        if not v:
            raise ValueError('Items list cannot be empty')
        return v

order = Order(items=["apple", "banana"], total=5.99)
print(order)

Practice

Create a Pydantic model for a complex form with validation.

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement