Replace repetitive constructor and representation code with a dataclass.
What You Will Learn
The @dataclass decorator generates methods such as __init__, __repr__ and __eq__ from annotated fields. It is well suited to simple records where fields are the main concern. Use field(default_factory=list) for mutable collections; dataclasses do not validate runtime types merely because annotations are present.
Class interfaces should preserve their stated invariants. Type annotations describe intent but do not enforce runtime types on their own.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from dataclasses import dataclass, field
@dataclass
class Order:
order_id: int
items: list[str] = field(default_factory=list)
order = Order(42)
order.items.append("Notebook")
print(order)
print(Order(42).items)
How the Example Works
- The imports provide the standard-library tools used in the demonstration: dataclasses.
- The class Order groups data and behavior; its methods run when called on an instance.
- The variable order holds the result of Order(42). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
Order(order_id=42, items=['Notebook'])
[]
When You Would Use This
A class becomes useful when several operations must maintain rules around related data. Think about which state belongs to each instance, which operations should be public, and how errors should be reported. Avoid making the design more complex than the underlying task.
Practice: Modify the Code
Add a total field and compare the automatically generated representation with the ordinary class version.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Replacing the factory with a mutable shared default such as items = [].
- Assuming @dataclass enforces order_id to be an int at runtime without validation.
Key Takeaways
- Replace repetitive constructor and representation code with a dataclass.
- The @dataclass decorator generates methods such as __init__, __repr__ and __eq__ from annotated fields.
- Apply this operation only after checking the assumptions and input conditions shown in the example.