Object-oriented Python and maintainable design · Lesson 2 of 3
Dataclasses, composition, and special methods
Represent structured data cleanly without building unnecessary class boilerplate.
Lesson
1. Concept and mental model
The dataclasses module can generate common methods for classes whose main purpose is to hold structured data. @dataclass can provide a readable representation and comparisons, while type annotations describe intended fields. Use field(default_factory=list) for a per-instance mutable default. Dataclasses do not automatically validate every value at runtime; validation remains an explicit responsibility of the constructor or a dedicated boundary layer.
2. How it works
Composition lets a class delegate work to collaborators. For example, a report generator can receive a storage object rather than inheriting from a specific cloud provider’s implementation. This separation makes dependencies replaceable in tests and prevents a class hierarchy from becoming a rigid web of special cases. Define a narrow interface for the operations the class actually needs.
3. Use it safely and effectively
Python special methods such as __str__, __repr__, and __eq__ integrate an object with built-in operations. Implement them when their behavior is intuitive and consistent with the data model. Do not overload operators in a surprising way. Choose frozen dataclasses for values that should not change after creation, but note that immutability is shallow unless contained objects are immutable too.
4. Syntax reference
from dataclasses import dataclass, field
@dataclass
class Batch:
name: str
records: list[str] = field(default_factory=list)
first = Batch('orders')
second = Batch('users')
first.records.append('order-1')
print(second.records)5. Guided walkthrough
Use a dataclass when the main purpose of a class is to hold related fields, and give mutable fields a default factory. Compose a larger object from smaller collaborators when each part has a clear responsibility and can be tested independently.
6. Common mistakes to avoid
- Using a mutable dataclass default shared by every instance instead of field(default_factory=...).
- Choosing inheritance solely to reuse a few lines when composition gives clearer ownership.
Visual guide
Compose a data model
-
Step 01
Describe
Define the values a type represents.
-
Step 02
Collaborate
Delegate external work to a focused object.
-
Step 03
Verify
Test the behavior with replaceable collaborators.
Code examples
from dataclasses import dataclass, field
@dataclass
class Batch:
name: str
records: list[str] = field(default_factory=list)
first = Batch('orders')
second = Batch('users')
first.records.append('order-1')
print(second.records)
[]
from dataclasses import dataclass, field
@dataclass
class Cart:
items: list[str] = field(default_factory=list)
print(Cart())
Cart(items=[])
class EmailSender:
def send(self, address: str) -> str:
return f'Sent to {address}'
class ReceiptService:
def __init__(self, sender: EmailSender) -> None:
self.sender = sender
print(ReceiptService(EmailSender()).sender.send('a@example.com'))
Sent to a@example.com
Key points
- Represent structured data cleanly without building unnecessary class boilerplate.
- Prefer explicit, testable behavior over hidden side effects.
- Validate assumptions at system boundaries and handle failure deliberately.
Check your understanding
Practice
Your learning progress