Classes and dataclasses
Course contents (15 lessons)
- Iteration the Python way
- List, dict and set comprehensions
- Iterators and generators
- Functions as building blocks
- Closures and decorators
- Context managers and the with statement
- Object-oriented Python in depth
- Classes and dataclasses
- Properties and special (dunder) methods
- Inheritance versus composition
- Quality: types, packaging and tests
- Type hints and mypy
- Packaging a project with pyproject.toml
- Testing with pytest
- Async code and web APIs
- async and await with asyncio
- Working with HTTP APIs and JSON
- Performance, concurrency and a final project
- Performance and profiling
- Concurrency: threads versus processes
- Final project: a price tracker command-line tool
Why a class at all
A class groups data with the functions that work on that data. If you pass the same three dictionaries into five functions, a class may be what you want. If you just need a bag of values, a dictionary or a dataclass is enough. A class is not automatically better.
A plain class
class InvoiceLine:
tax_rate = 0.17 # class attribute: shared by all
def __init__(self, description, unit_price, quantity=1):
self.description = description # instance attributes
self.unit_price = unit_price
self.quantity = quantity
def total(self):
return self.unit_price * self.quantity * (1 + self.tax_rate)
def __repr__(self):
return f"InvoiceLine({self.description!r}, {self.unit_price}, {self.quantity})"
__init__ runs when you create an object. The first parameter, self, is the object itself, and Python passes it automatically. Attributes set on self belong to that one object. An attribute set in the class body, like tax_rate, is shared by all instances. Python looks in the instance first, then the class.
This is a lot of typing for a simple record: we wrote each field three times (in the parameters, on the left, and on the right), and we had to write __repr__ by hand. We do not even have equality: InvoiceLine("a", 1) == InvoiceLine("a", 1) is False, because the default compares object identity.
Dataclasses
The dataclasses module generates the boring parts from type-annotated fields.
from dataclasses import dataclass, field
@dataclass
class InvoiceLine:
description: str
unit_price: float
quantity: int = 1
def total(self, tax_rate: float = 0.17) -> float:
return round(self.unit_price * self.quantity * (1 + tax_rate), 2)
@dataclass(order=True)
class Invoice:
number: str
customer: str
lines: list[InvoiceLine] = field(default_factory=list, compare=False)
def add(self, line: InvoiceLine) -> None:
self.lines.append(line)
def total(self) -> float:
return round(sum(line.total() for line in self.lines), 2)
a = InvoiceLine("Paper ream", 1250.5, 4)
b = InvoiceLine("Paper ream", 1250.5, 4)
print(a)
print(a == b)
inv = Invoice("INV-001", "Ali Traders")
inv.add(a)
inv.add(InvoiceLine("Stapler", 480))
print(inv.total())
print(Invoice("INV-001", "X") < Invoice("INV-002", "X"))
Output:
InvoiceLine(description='Paper ream', unit_price=1250.5, quantity=4)
True
6413.94
True
We get __init__, __repr__ and __eq__ for free. With order=True we also get comparison operators that compare fields in order, so invoices sort by number first. The invoice total is 5852.34 for the paper plus 561.60 for the stapler, which is 6413.94.
Mutable defaults and field()
This is the one mistake that dataclasses actively stop you from making. Writing lines: list = [] raises a ValueError, because one shared list would be reused by every instance. Use field(default_factory=list) so each object gets a new list. The same warning applies to ordinary function defaults, as the beginner course explained.
Useful options
| Option | Effect |
|---|---|
frozen=True | Instances cannot be changed after creation, and they become hashable. |
order=True | Adds <, <=, >, >=. |
slots=True | Uses less memory and blocks accidental new attributes. |
kw_only=True | All fields must be passed by name. |
@dataclass(frozen=True, slots=True)
class Money:
amount: int # in paisa, to avoid float errors
currency: str = "PKR"
price = Money(150_000)
# price.amount = 1 # raises FrozenInstanceError
Frozen dataclasses are a good choice for value objects like money or coordinates. Values that never change are easier to reason about, and you can use them as dictionary keys.
__post_init__
For validation or derived fields, define __post_init__. It runs after the generated __init__.
@dataclass
class Discount:
percent: float
def __post_init__(self):
if not 0 <= self.percent <= 100:
raise ValueError("percent must be between 0 and 100")
Converting to plain data
dataclasses.asdict(obj) turns an instance into a dictionary, including nested dataclasses. That makes saving to JSON easy.
Common mistakes
- Forgetting the annotation. Only names with a type annotation become fields.
quantity = 1without: intis just a class attribute. - Field order with defaults. A field without a default cannot follow one that has a default. Python raises
TypeError. - Expecting type checking at runtime. Annotations are hints.
InvoiceLine("x", "oops")works. Use mypy or validate manually. - Mutating a frozen instance. Use
dataclasses.replace(obj, field=new_value)to get a modified copy.
Try it yourself
Create a frozen dataclass Point with x and y and a method distance_to(other) using math.hypot. Create a Polygon dataclass holding a list of points, with a perimeter() method. Check that two points with equal coordinates compare equal, and use a point as a dictionary key.
from dataclasses import dataclass, field
@dataclass
class InvoiceLine:
description: str
unit_price: float
quantity: int = 1
def total(self, tax_rate: float = 0.17) -> float:
return round(self.unit_price * self.quantity * (1 + tax_rate), 2)
@dataclass(order=True)
class Invoice:
number: str
customer: str
lines: list[InvoiceLine] = field(default_factory=list, compare=False)
def add(self, line: InvoiceLine) -> None:
self.lines.append(line)
def total(self) -> float:
return round(sum(line.total() for line in self.lines), 2)
a = InvoiceLine("Paper ream", 1250.5, 4)
b = InvoiceLine("Paper ream", 1250.5, 4)
print(a)
print(a == b)
inv = Invoice("INV-001", "Ali Traders")
inv.add(a)
inv.add(InvoiceLine("Stapler", 480))
print(inv.total())
print(Invoice("INV-001", "X") < Invoice("INV-002", "X"))
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account