Programming Search⌘K

Featurecore

Rich comparison methods

Also called __eq__, __lt__, __le__, __gt__, __ge__, __ne__, __hash__, NotImplemented, functools.total_ordering, compare objects.

The six methods __lt__, __le__, __eq__, __ne__, __gt__ and __ge__ implement the comparison operators. A class that defines __eq__ but not __hash__ becomes unhashable.

Language
Python

Synopsis

from functools import total_ordering

@total_ordering
class Version:
    def __init__(self, major, minor):
        self.major, self.minor = major, minor

    def _key(self):
        return (self.major, self.minor)

    def __eq__(self, other):
        if not isinstance(other, Version):
            return NotImplemented
        return self._key() == other._key()

    def __lt__(self, other):
        if not isinstance(other, Version):
            return NotImplemented
        return self._key() < other._key()

    def __hash__(self):
        return hash(self._key())

    def __repr__(self):
        return f"Version({self.major}, {self.minor})"

vs = [Version(3, 12), Version(2, 7), Version(3, 9)]
print(sorted(vs))
print(Version(3, 9) <= Version(3, 12), Version(3, 9) == Version(3, 9), Version(1, 0) == "1.0")
print(len({Version(3, 9), Version(3, 9)}))
Output
[Version(2, 7), Version(3, 9), Version(3, 12)]
True True False
1

The class defines __eq__ and __lt__, and total_ordering adds <=, > and >=. __hash__ uses the same key as __eq__, so equal versions are one item in a set.

Semantics

r1. "These are the so-called “rich comparison” methods. The correspondence between operator symbols and method names is as follows: x<y calls x.lt(y), x<=y calls x.le(y), x==y calls x.eq(y), x!=y calls x.ne(y), x>y calls x.gt(y), and x>=y calls x.ge(y)."1

r2. "A rich comparison method may return the singleton NotImplemented if it does not implement the operation for a given pair of arguments."1 "When no appropriate method returns any value other than NotImplemented, the == and != operators will fall back to is and is not, respectively."1

r3. "By default, the object class provides implementations consistent with Value comparisons: equality compares according to object identity, and order comparisons raise TypeError."1 "For ne(), by default it delegates to eq() and inverts the result unless it is NotImplemented. There are no other implied relationships among the comparison operators or default implementations".1 Examples: default, le-missing.

r4. "There are no swapped-argument versions of these methods".1 Instead, "lt() and gt() are each other’s reflection, le() and ge() are each other’s reflection, and eq() and ne() are their own reflection."1 Example: reflected.

r5. "Given a class defining one or more rich comparison ordering methods, this class decorator supplies the rest."2 "The class must define one of lt(), le(), gt(), or ge(). In addition, the class should supply an eq() method."2

r6. "The only required property is that objects which compare equal have the same hash value".1 "A class that overrides eq() and does not define hash() will have its hash() implicitly set to None."1 Then its instances "raise an appropriate TypeError when a program attempts to retrieve their hash value".1 Examples: hash-none, unhashable.

r7. "If a class defines mutable objects and implements an eq() method, it should not implement hash(), since the implementation of hashable collections requires that a key’s hash value is immutable".1

Examples

class Plain:
    pass

a, b = Plain(), Plain()
print(a == a, a == b, a != b)
Output
True False True

Without __eq__, two objects are equal only when they are the same object (rule r3).

class Meters:
    def __init__(self, n):
        self.n = n

    def __lt__(self, other):
        print("Meters.__lt__")
        return self.n < other if isinstance(other, int) else NotImplemented

    def __gt__(self, other):
        print("Meters.__gt__")
        return self.n > other if isinstance(other, int) else NotImplemented

print(5 < Meters(3))
Output
Meters.__gt__
False

int does not know Meters, so 5 < m becomes m > 5, the reflection of < (rule r4).

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.y)

print(Point(1, 2) == Point(1, 2), Point.__hash__)
Output
True None

Pitfalls

__eq__ without __hash__ makes the class unhashable, so its instances cannot go in a set or be dict keys:

This code raises TypeError, on purpose.

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.y)

{Point(1, 2)}

Add a __hash__ that hashes the same fields as __eq__, if the objects do not change (rules r6 and r7).

__lt__ and __eq__ do not give <=:

This code raises TypeError, on purpose.

class Score:
    def __init__(self, n):
        self.n = n

    def __lt__(self, other):
        return self.n < other.n

    def __eq__(self, other):
        return self.n == other.n

Score(1) <= Score(2)

Define __le__ too, or use total_ordering (rules r3 and r5).

Comparison

Go compares structs field by field, with no methods: "Struct types are comparable if all their field types are comparable. Two struct values are equal if their corresponding non-blank field values are equal."3 "The ordering operators <, <=, >, and >= apply to operands of ordered types."3 A struct is not in the list of ordered types. In Python a class chooses what == and < mean (rule r1).

References

  1. The Python Language Reference, 3. Data model, 3.3.1. Basic customization, object.__lt__() to object.__ge__(); object.__hash__()
  2. functools, Higher-order functions and operations on callable objects, functools.total_ordering
  3. The Go Programming Language Specification, Comparison operators

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source