Incomplete ordering¶
ID: py/incomplete-orderingKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - reliability - correctnessQuery suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
A class that implements the rich comparison operators (__lt__,__gt__,__le__, or__ge__) should ensure that all four comparison operations<,<=,>, and>= function as expected, consistent with expected mathematical rules. In Python 3, this is ensured by implementing one of__lt__ or__gt__, and one of__le__ or__ge__. If the ordering is not consistent with default equality, then__eq__ should also be implemented.
Recommendation¶
Ensure that at least one of__lt__ or__gt__ and at least one of__le__ or__ge__ is defined.
Thefunctools.total_ordering class decorator can be used to automatically implement all four comparison methods from a single one, which is typically the cleanest way to ensure all necessary comparison methods are implemented consistently.
Example¶
In the following example, only the__lt__ operator has been implemented, which would lead to unexpected errors if the<= or>= operators are used onA instances. The__le__ method should also be defined, as well as__eq__ in this case.
classA:def__init__(self,i):self.i=i# BAD: le is not defined, so `A(1) <= A(2)` would result in an error.def__lt__(self,other):returnself.i<other.i
References¶
Python Language Reference:Rich comparisons in Python.