Dataclasses, NamedTuple & Pydantic
Use @dataclass for auto-generated boilerplate, NamedTuple for immutable records, and Pydantic v2 for validated data models with JSON serialization.
Part 1: What You Will Learn
- Reduce class boilerplate with
@dataclass. - Use
NamedTuplefor lightweight immutable records. - Validate external data with Pydantic v2.
- Choose the right model type for internal data versus untrusted input.
Part 2: Key Concepts
These three tools all describe structured data, but they solve different problems. Dataclasses are excellent for normal Python domain objects, NamedTuple is compact and immutable, and Pydantic is designed for parsing and validating data from forms, files, APIs, and other external sources.
Part 3: Topic-Specific Code Examples
from dataclasses import dataclass, field
from typing import NamedTuple
@dataclass(slots=True)
class Student:
student_id: str
name: str
marks: list[int] = field(default_factory=list)
@property
def average(self) -> float:
return sum(self.marks) / len(self.marks) if self.marks else 0.0
class GradeSummary(NamedTuple):
student_id: str
average: float
passed: bool
student = Student("S001", "Aisha", [78, 82, 91])
summary = GradeSummary(
student.student_id,
student.average,
student.average >= 50,
)
print(student)
print(summary)# Install once: pip install pydantic
from pydantic import BaseModel, Field, ValidationError
class StudentInput(BaseModel):
student_id: str = Field(min_length=3, max_length=12)
name: str = Field(min_length=2)
mark: int = Field(ge=0, le=100)
try:
data = StudentInput(student_id="S002", name="Daniel", mark=87)
print(data.model_dump())
print(data.model_dump_json())
except ValidationError as exc:
print(exc)Part 4: How the Example Works
The dataclass automatically provides an initializer and readable representation. default_factory=list gives each student a separate marks list. The NamedTuple summary cannot be modified after creation. Pydantic validates field length and the mark range before the model is accepted, then can serialize the model to dictionaries or JSON.
Part 5: Hands-On Practice
Mini project โ Product Import Validator. Model an internal Product with @dataclass, use a NamedTuple for a price summary, and create a Pydantic ProductInput model that rejects negative prices and blank names.
Part 6: Next Steps
Run and modify the examples in Visual Studio 2026, then continue to Lesson 13. Return to Python Tutorial Home to review the complete curriculum.