mfgustavo
mfgustavo

Reputation: 93

Override all Python comparison methods in one declaration

Suppose you have a simple class like A below. The comparison methods are all virtually the same except for the comparison itself. Is there a shortcut around declaring the six methods in one method such that all comparisons are supported, something like B?

I ask mainly because B seems more Pythonic to me and I am surprised that my searching didn't find such a route.

class A:
    def __init__(self, number: float, metadata: str):
        self.number = number
        self.metadata = metadata

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

    def __le__(self, other):
        return self.number <= other.number

    def __gt__(self, other):
        return self.number > other.number

    def __ge__(self, other):
        return self.number >= other.number

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

    def __ne__(self, other):
        return self.number != other.number


class B:
    def __init__(self, number: float, metadata: str):
        self.number = number
        self.metadata = metadata

    def __compare__(self, other, comparison):
        return self.number.__compare__(other.number, comparison)

Upvotes: 8

Views: 5172

Answers (2)

Frodon
Frodon

Reputation: 3775

The functools module provides the total_ordering decorator which is meant to provide all comparison methods, given that you provide at least one from __lt__(), __le__(), __gt__(), or __ge__().

See this answer from Martijn Pieters.

Upvotes: 7

wasif
wasif

Reputation: 15498

To do it easier, python standard library ships with a module named operator.

It has the methods like operator.__eq__ or operator.__ge__ and so on. So if you want to compare you can easily call them like methods and compare.

Upvotes: 0

Related Questions