Lesson contents

Python — Modeling records with dataclasses

A Python dataclass declares fields using type annotations and can generate an initializer. A method or property can compute a subtotal from the stored quantity and unit price.

A simple example

Read one field

  1. Start with A point with x = 2
  2. Do this Read x
  3. Result 2
A record keeps related values together. Here the program reads a single named field.
lesson.py
from dataclasses import dataclass

@dataclass
class Point:
    x: int

print(Point(2).x)
Output
2
Advertisements

Represent an invoice line

The dataclass decorator generates construction and equality methods from the annotated fields. frozen=True prevents ordinary assignment to those fields. The subtotal is a derived value.

One line item: 3 juices. Price per juice: 125¢. Subtotal: 375¢.
Keep an invoice line together

A café invoice lists three juices at 125 cents each. Store the quantity and price together, then calculate the subtotal when the receipt is printed. Changing the quantity can then update the total automatically.

Run the example

Python 3.8 or later. Run these commands from the directory containing the example.

python3 lesson.py
lesson.py
from dataclasses import dataclass

@dataclass(frozen=True)
class LineItem:
    units: int
    cents: int

    def subtotal(self):
        return self.units * self.cents

line = LineItem(3, 125)
print(line.subtotal())
Output
375

The line holds three units at 125 cents each. Multiplication gives 375 cents. Keeping the subtotal derived means there is no third field that can become stale.

Try it yourself

Create a second line with two units at 90 cents each.

Check your answer

Its subtotal is 180 cents. The two subtotals together are 555 cents before any taxes or delivery charges.

The Python Tutorial

Related tags

  • Python
  • data modeling
  • records
  • methods