PYTHON / CHAPTER 15

Records, ordering, and invariants

Advanced

Model data explicitly and reason about repeatable ordering.

By the end of this chapter

  • Define lightweight records with dataclasses
  • Compose stable sorting rules
  • Recognize the limits of frozen records

The idea

A dataclass generates routine record methods from annotated fields, helping a program expose meaningful names instead of positional conventions. Type annotations document intent but do not automatically validate incoming runtime data. A frozen dataclass prevents normal reassignment of its fields; it does not recursively freeze a list stored in a field. Prefer immutable field values when the record must remain dependable.

Sorting is a separate policy from record storage. Python sorting is stable, so equal keys retain their earlier relative order. A tuple key expresses primary and secondary rules directly, and sorted returns a new list. Explain ties explicitly rather than depending on incidental input order when a report needs a unique order. Validate boundary data before constructing records that internal code treats as trustworthy.

Python example
from dataclasses import dataclass

@dataclass(frozen=True)
class Entry:
    name: str
    score: int

rows = [Entry("Bo", 8), Entry("Ada", 8), Entry("Cy", 5)]
print([r.name for r in sorted(rows, key=lambda r: (-r.score, r.name))])
Result
['Ada', 'Bo', 'Cy']

Negating score gives descending numeric order, while the name provides an ascending tie-breaker. sorted leaves the original list order unchanged.

Try it yourself

Define a frozen result record and return a sorted report with an explicit tie-breaker and no input mutation.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

Open Python coding challenges

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does frozen=True guarantee in ordinary dataclass use?