There is no standard 'comparable' ABC, no, as the rich comparison methods are really very flexible and don't necessarily return booleans.
The default built-in types return NotImplemented
when applied to a type they can't be compared with, for example, while specialised libraries like SQLAlchemy and numpy use rich comparison methods to return completely different objects. See the documentation for the rich comparison methods for the details.
But you should be able to define a
a Protocol
subclass for specific expectations:
from typing import Protocol, TypeVar
T = TypeVar("T")
class Comparable(Protocol[T]):
def __eq__(self: T, other: T) -> bool:
...
def __lt__(self: T, other: T) -> bool:
...
# ... etc
You may need to tweak the protocol to fit your exact expectations, and / or use a non-generic version that's specific to the types you use (perhaps with @overload
ed definitions for specific types).
For sorting with the builtin sorted()
function, __eq__
and __lt__
suffice.