Use order=True, slots=True, and kw_only=True to shape dataclass behavior.
What You Will Learn
order=True generates ordering comparisons from comparable fields; slots=True avoids a normal instance __dict__ in typical cases; kw_only=True requires keyword arguments for fields. These flags are independent and solve different design needs.
Using slots may affect weak references and multiple-inheritance compatibility.
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
@dataclass(order=True, slots=True, kw_only=True)
class Task:
priority: int
title: str
first_task = Task(priority=1, title="Review")
second_task = Task(priority=2, title="Deploy")
print(first_task < second_task)
print(first_task.title)
How the Example Works
- The imports provide the standard-library tools used in the demonstration: dataclasses.
- The class Task groups data and behavior; its methods run when called on an instance.
- The variable first_task holds the result of Task(priority=1, title='Review'). Later lines use that value or inspect how it changes.
- The variable second_task holds the result of Task(priority=2, title='Deploy'). Later lines use that value or inspect how it changes.
Expected output from the example:
True
Review
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
Declare two tasks and compare them by field-order tuple semantics.
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
- Trying positional construction after setting kw_only=True.
- Assuming order=True sorts by just one field regardless of declaration order.
Key Takeaways
- Use order=True, slots=True, and kw_only=True to shape dataclass behavior.
- order=True generates ordering comparisons from comparable fields; slots=True avoids a normal instance __dict__ in typical cases; kw_only=True requires keyword arguments for fields.
- Using slots may affect weak references and multiple-inheritance compatibility.