Generate data-class methods with @dataclass.
What You Will Learn
@dataclass inspects type-annotated fields and can generate __init__, __repr__, and __eq__. It supports configuration for immutability-like assignment blocking, ordering, and slots.
Default equality compares instances of the same dataclass type field by field.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from dataclasses import dataclass
@dataclass(order=True)
class Priority:
level: int
label: str
print(Priority(1, "urgent") < Priority(2, "normal"))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: dataclasses.
- The class Priority groups data and behavior; its methods run when called on an instance.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression Priority(1, 'urgent') < Priority(2, 'normal') prints True. Compare that result with the rule above before you change the argument.
Expected output from the example:
True
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Define two records with explicit default values and compare their repr outputs.
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
- Assuming dataclass generates ordering methods without order=True.
- Expecting frozen=True to recursively freeze nested lists and dictionaries.
Key Takeaways
- Generate data-class methods with @dataclass.
- @dataclass inspects type-annotated fields and can generate __init__, __repr__, and __eq__.
- Default equality compares instances of the same dataclass type field by field.