Generate missing comparison methods from a minimal supported set.
What You Will Learn
total_ordering requires __eq__ and at least one ordering method such as __lt__. It synthesizes remaining comparisons but adds overhead relative to writing all methods explicitly.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from functools import total_ordering
@total_ordering
class Priority:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return isinstance(other, Priority) and self.value == other.value
def __lt__(self, other):
if not isinstance(other, Priority):
return NotImplemented
return self.value < other.value
print(Priority(2) <= Priority(5))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: functools.
- 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(2) <= Priority(5) 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
Implement equality and less-than for a custom rank object.
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
- Forgetting __eq__ or returning False instead of NotImplemented for unsupported comparison types.
- Using a wrapper without checking which original function, arguments and return values it preserves.
Key Takeaways
- Generate missing comparison methods from a minimal supported set.
- total_ordering requires __eq__ and at least one ordering method such as __lt__.
- Apply this operation only after checking the assumptions and input conditions shown in the example.