Dataclasses, Enums and Pydantic Models

Represent structured domain data with dataclasses, make finite states explicit with enums, and validate untrusted input with Pydantic.

Est. 45 min Updated Suggest a fix
// Part 01 — Three Different Jobs

Choose the Right Shape for the Data

As a Python program grows, plain dictionaries become hard to reason about: keys can be misspelled, the expected shape is not obvious, and every caller repeats validation. Three tools address different parts of that problem. A dataclass concisely represents trusted, in-process domain data. An Enum names a fixed set of choices such as an order state. Pydantic validates and parses data arriving from outside your program, such as JSON or an API request.

These are not competing ways to write a class. A delivery service might use a Pydantic model at its HTTP boundary, convert validated values into a dataclass used by business logic, and use an enum for the order lifecycle. A dataclass's annotations improve editor and type-checker support, but Python does not automatically enforce them at runtime.

💡 Note
Prerequisites: classes, constructors, type hints, dictionaries, and exceptions. This lesson builds on the OOP sequence through Lesson 25 and the type-hint lesson (Lesson 38).
// Part 02 — Dataclasses

Remove Constructor Boilerplate, Keep the Domain Model

The standard-library dataclasses module generates common methods from annotated fields. Use @dataclass when the class primarily stores data and its behavior is modest. The generated initializer accepts fields in declaration order, while the generated representation is useful for debugging.

A compact domain object
from dataclasses import dataclass

@dataclass
class Delivery:
    order_id: str
    customer: str
    total_paise: int
    city: str

delivery = Delivery("ORD-1042", "Asha", 129900, "Hyderabad")
print(delivery)
print(delivery.total_paise)

Money is stored here in paise as an integer, not a binary floating-point amount of rupees. This avoids common rounding surprises in arithmetic. Formatting for display can convert to rupees at the boundary, while calculations keep a precise representation.

Default values need a factory when mutable
from dataclasses import dataclass, field

@dataclass
class Batch:
    name: str
    order_ids: list[str] = field(default_factory=list)

morning = Batch("morning")
evening = Batch("evening")
morning.order_ids.append("ORD-1")
print(evening.order_ids)  # [] — each instance has its own list
⚠️ Important
Never write order_ids: list[str] = [] as a dataclass default. That one list would be shared by every instance. default_factory calls a function for each new object.
// Part 03 — Dataclass Options

Equality, Ordering, Immutability and Boundaries

By default, dataclasses provide a useful representation and value-based equality. Two instances with the same class and equal field values compare equal. You can mark a value object as frozen=True when reassignment should be rejected, but frozen is shallow: a list stored in a frozen object can still be mutated. Prefer immutable field types such as tuples when deep immutability matters.

An immutable value object
from dataclasses import dataclass

@dataclass(frozen=True)
class Coordinates:
    latitude: float
    longitude: float

home = Coordinates(17.385, 78.4867)
# home.latitude = 18.0  # raises dataclasses.FrozenInstanceError

Dataclasses do not validate field types. Delivery("ORD-2", "Ravi", "cheap", "Chennai") can be constructed despite the annotated integer total. Use constructors or explicit validation for internal invariants; use Pydantic when values need parsing and validation from untrusted input.

// Part 04 — Enums

Replace Unclear Strings with Named States

A status field often starts as a string and gradually collects spelling variants such as "in-transit", "in_transit", and "In Transit". An enum gives each valid choice one canonical name. A string enum can serialize naturally while keeping comparisons explicit.

An order lifecycle
from enum import Enum

class DeliveryStatus(str, Enum):
    PLACED = "placed"
    CONFIRMED = "confirmed"
    IN_TRANSIT = "in_transit"
    DELIVERED = "delivered"
    CANCELLED = "cancelled"

status = DeliveryStatus.IN_TRANSIT
print(status.value)                 # in_transit
print(status == DeliveryStatus.IN_TRANSIT)  # True

Use enum members in business logic rather than repeatedly comparing strings. Keep transitions deliberate: an enum defines the possible values, but does not by itself enforce that a delivered order cannot move back to placed. A transition function or domain method should enforce that rule.

Enforce transitions in one place
ALLOWED = {
    DeliveryStatus.PLACED: {DeliveryStatus.CONFIRMED, DeliveryStatus.CANCELLED},
    DeliveryStatus.CONFIRMED: {DeliveryStatus.IN_TRANSIT, DeliveryStatus.CANCELLED},
    DeliveryStatus.IN_TRANSIT: {DeliveryStatus.DELIVERED},
    DeliveryStatus.DELIVERED: set(),
    DeliveryStatus.CANCELLED: set(),
}

def move_to(current: DeliveryStatus, target: DeliveryStatus) -> DeliveryStatus:
    if target not in ALLOWED[current]:
        raise ValueError(f"Cannot move from {current.value} to {target.value}")
    return target
// Part 05 — Pydantic at the Boundary

Parse External Data, Don't Trust Its Shape

Pydantic is a third-party library, so install it in the project virtual environment with pip install pydantic. Its model declarations look similar to dataclasses, but Pydantic performs runtime parsing and validation. In this example, a JSON payload is untrusted until the model accepts it.

Validated request model
from pydantic import BaseModel, ConfigDict, Field

class DeliveryRequest(BaseModel):
    model_config = ConfigDict(extra="forbid")

    order_id: str = Field(min_length=1)
    customer: str = Field(min_length=1)
    total_paise: int = Field(gt=0)
    city: str = Field(min_length=1)

payload = {
    "order_id": "ORD-1042",
    "customer": "Asha",
    "total_paise": 129900,
    "city": "Hyderabad",
}
request = DeliveryRequest.model_validate(payload)
print(request.model_dump())

Validation can fail with pydantic.ValidationError; handle it at the boundary and return a clear client error rather than allowing invalid data into business logic. Pydantic may coerce compatible inputs according to its validation rules, so choose strictness intentionally if coercion is not appropriate for a field. The model validates data; it does not replace authorization, database constraints, or business-rule checks.

🎯 Pro Tip
A clean flow is: external JSON → Pydantic request model → domain object or service call → response model. Keep transport-specific validation out of core business functions where practical.
// Part 06 — Serialization and Model Choice

Choose by Responsibility, Not Familiarity

NeedGood fitImportant limit
Plain internal value objectdataclassAnnotations are not runtime validation
Finite named set of statesEnumDoes not enforce valid state transitions
Validate incoming JSON or API dataPydantic modelThird-party dependency; define coercion policy
Complex behavior and invariantsRegular class or domain serviceChoose explicit logic over decorator magic

Standard JSON encoding does not automatically know how to serialize every dataclass or enum. Convert deliberately: use dataclasses.asdict() for dataclasses, and the enum's .value for its wire representation. For Pydantic models, model_dump() returns Python data and model_dump_json() emits JSON text.

Explicit conversion for a dataclass
from dataclasses import asdict
import json

record = Delivery("ORD-1042", "Asha", 129900, "Hyderabad")
print(json.dumps(asdict(record)))
// Part 07 — Common Mistakes

Modeling Errors to Catch Early

  • Treating annotations as checks: dataclasses do not enforce field types. Validate external input with Pydantic or explicit code.
  • Using a mutable literal default: lists and dictionaries can be shared. Use field(default_factory=...).
  • Assuming frozen means deeply immutable: nested mutable objects remain mutable. Prefer immutable members or copy defensively.
  • Using raw strings for lifecycle states: misspellings become hidden states. Use an enum and separately validate transitions.
  • Assuming Pydantic is authorization: schema validity does not prove a user may act on a record. Authorize in application logic.
📌 Real World Example
For an order API, Pydantic can confirm total_paise is a positive integer and the order identifier is present. The service must still confirm the caller owns the order and that its current status allows cancellation.
// Part 08 — Practice

Practice: Model a Small Service Domain

  1. Create a @dataclass for a support ticket with an identifier, title, and list of notes. Prove each new instance has its own notes list.
  2. Create an enum for ticket status and write a transition function that rejects reopening a permanently closed ticket.
  3. Write a Pydantic request model that rejects empty titles and unknown fields. Try valid, missing, and invalid input.
  4. Convert a dataclass to a JSON-compatible dictionary and serialize the enum as its stable string value.
  5. Decide which checks belong at input parsing, in the domain model, and in an authorization layer; explain why.

Suggested check: use pytest to assert that invalid payloads raise ValidationError, illegal transitions raise ValueError, and valid transitions return the requested enum member.

🎯 Key Takeaways

  • ✓Dataclasses generate useful boilerplate for data-focused classes; their annotations do not perform runtime validation.
  • ✓Use field(default_factory=...) for mutable dataclass fields so instances do not share the same collection.
  • ✓Frozen dataclasses prevent field reassignment but do not recursively freeze nested values.
  • ✓Enums replace scattered string constants with a finite, named set of values; validate state transitions separately.
  • ✓Pydantic parses and validates untrusted input at runtime; it is a third-party dependency, not a substitute for authorization.
  • ✓Keep parsing, domain rules, persistence, and output serialization as explicit boundaries.

What comes next

Lesson 27 moves into flexible function signatures with positional, keyword, and variadic arguments.

Lesson 27 → *args, **kwargs and Function Arguments Deep Dive

HELP US IMPROVE

How was this lesson?

Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.

Choose your feedback

Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.

Share

Discussion

0

Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.

Continue with GitHub
Loading...