Type hints and dataclasses

Annotations, Optional, and a frozen dataclass for a row.

Hints tell readers (and later, checkers) what a function expects. They are not enforced at runtime unless you add a library. A dataclass is a small class for a row of data.

Goal

Annotate line_total, use Optional, and define a frozen Item.

Annotations

def line_total(units: int, price: float, tax: float = 0.16) -> float:
    return round(units * price * (1 + tax), 2)

print(line_total(2, 10.5))
print(line_total.__annotations__)

Optional

from typing import Optional

def city_label(city: Optional[str]) -> str:
    return str(city or "").strip().title()

print(city_label("Nairobi"))
print(city_label(None))

dataclass

from dataclasses import dataclass

@dataclass(frozen=True)
class Item:
    product: str
    units: int
    price: float

    def line_total(self, tax: float = 0.16) -> float:
        return round(self.units * self.price * (1 + tax), 2)

row = Item("A", 12, 10.5)
print(row)
print(row.line_total())

frozen=True makes the row immutable — handy for values you do not want to mutate by accident.

Tip

Hints are documentation that tools can read. This editor will not fail a call with the wrong type. Still write them on public functions.