LevelJar Sign in

Python course / Advanced

Dataclasses and the data model

Let a dataclass write the boilerplate, and learn the methods Python calls on your behalf. A changeable object used as a dictionary key disappears from the dictionary the moment you change it.

  • fields
  • default_factory
  • __post_init__
  • frozen and replace
  • ordering
  • hashing
  • __call__
  • descriptors

Start this module

Runs in your browser. Start straight away; create an account when you want your progress kept.

frozen records, changed by replacement
from dataclasses import dataclass, replace


@dataclass(frozen=True, order=True)
class Item:
    name: str
    pence: int
    tags: tuple[str, ...] = ()

    def __post_init__(self):
        if self.pence < 0:
            raise ValueError("pence cannot be negative")


tea = Item("tea", 350, ("hot",))
cheaper = replace(tea, pence=300)

print(tea)
print(cheaper)
print("sorted:", sorted([tea, cheaper])[0].pence)
Item(name='tea', pence=350, tags=('hot',))
Item(name='tea', pence=300, tags=('hot',))
sorted: 300

What you will learn

The lessons in this module

  • What @dataclass writes for you
  • Defaults that are lists
  • __post_init__: checking and working things out
  • frozen dataclasses and replace
  • Equality, hashing and dataclasses
  • Ordering dataclasses
  • Dataclasses to JSON and back
  • Which shape for your data
  • Field order, defaults and kw_only
  • slots: catching the misspelt attribute
  • Objects you can call
  • __getattr__: answering for missing attributes
  • __setattr__: a rule for every assignment
  • Descriptors: how property works
  • __init_subclass__: classes that register themselves
  • __format__: your objects in f-strings
  • The hash that changed
  • When the magic is the problem
  • Capstone: one more field
  • Module review: the price list editor

Ready when you are

Start this module

Previous: Context managers. Next: functools and itertools. All modules are on the course page.