Dataclasses

Classes & Objects, lesson 6 of 6

🏗️ Classes & Objects, lesson 6 of 6

Dataclasses

Skip the boilerplate: auto-generated __init__, __repr__ and ==.

9 min

1 exercise

1 quiz

0/2 solved

Getting Python ready… examples can run in a moment.

Many classes mostly hold data, and writing __init__, __repr__ and __eq__ by hand gets repetitive. The @dataclass decorator writes them for you from a list of fields:

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

The : int parts are type hints. Python doesn't enforce them, but dataclasses use them to find the fields.

Example

A dataclass in action

You got __init__, a readable __repr__ and value-based == for free. Fields with defaults must come after fields without one.

Quiz

What does this print?

A dataclass is still a normal class: add methods and properties as usual.

For list or dict fields, use field(default_factory=list). Dataclasses refuse tags: list = [] to protect you from the shared-list trap you saw earlier.

Example

Methods and default_factory

Replace field(default_factory=list) with [] and run it: Python stops you with a ValueError.

Options worth knowing:

  • @dataclass(order=True) adds <, > and friends, comparing fields in order, so sorting works
  • @dataclass(frozen=True) makes objects read-only, and hashable, so they can go in sets
Example

Sortable, frozen versions

As text, "1.10" sorts before "1.2", but comparing number fields gets it right. Try vs[0].major = 2 to see frozen in action.

Exercise

Inventory report

  1. Turn Product into a dataclass with fields name: str, price: float and qty: int = 0.
  2. Add a method total_value() that returns price * qty.
  3. Set inventory_value to the sum of total_value() over stock, rounded to 2 decimals.