Skip to Content

How do type hints + dataclasses work together?

Category: Python Fundamentals

Answer

Type hints declare expectations (PEP 484, enforced by mypy strict). @dataclass is sugar for a class whose primary purpose is holding values: init, repr, eq are auto-generated. Combine: typed fields + auto-generated plumbing + Pydantic for runtime validation.

Concrete examples from the fca project context

Example 1

@dataclass class User: id: int; email: str; optional_age: int | None

Example 2

Pydantic v2: BaseModel validates on construction; .model_dump() for dict projection.

Example 3

mypy —strict catches Optional fields used as None without an isinstance check.

Data flow / flow chart

class fields, typed -> @dataclass
  typed + runtime check -> Pydantic BaseModel
  mypy --strict then enforces the contract

Takeaway

Type hints + dataclass = typed data; Pydantic adds runtime validation; mypy checks both ends.