Search code examples
pythonlistsortingcomparison-operators

Python: how to compare custom class member to builtin type


New to python so forgive me if this is obvious. Say I've created a custom class Foo, and make a list of Foo() instances mixed with ints, for example:

foo_list = [Foo() for _ in range(10)]
for i in range(10):
  foo_list.append(i)
# then the foo_list is mixed with Foo()s and ints

How can a Foo instance be comparable with an int? Basically my target is to make it possible to sort() the above list.


Solution

  • You can add __lt__ and __gt__ methods to the Foo class (less than and greater than) that evaluate Foo objects as being less than or greater than integers, this is used by sort when a key function is not provided

    class Foo():
    
        def __lt__(self, other):
            if isinstance(other, int):
                return self._id < other
            elif isinstance(other, self.__class__):
                return self._id < other._id
    
        def __gt__(self, other):
            if isinstance(other, int):
                return self._id > other
            elif isinstance(other, self.__class__):
                return self._id > other._id