'Setting the Comparison Value For All __lt__, __gt__, __eq__, etc?
Is it possible to set the comparison value for all comparison operations?
I've done something like this:
@dataclass
class _Leaf(Generic[T]):
parent: _Leaf
value: T
def __init__(self, value: Optional[T] = None):
self.value = value
self.parent = self
def update(self, value: T):
self.value = value
return self
def __lt__(self, other: _Leaf):
return repr(self) < repr(other)
def __gt__(self, other: _Leaf):
return repr(self) > repr(other)
def __eq__(self, other: _Leaf):
return repr(self) == repr(other)
def __repr__(self):
return self.value
But this is more of a convention rather than something built into python and I later found that this does not work when I want to compare tuples. I could come up with a __val__ of my own and use that but I don't want to add functionality if it already exists. Is there something like my proposed __val__ that I can use?
@dataclass
class _Leaf(Generic[T]):
parent: _Leaf
value: T
def __init__(self, value: Optional[T] = None):
self.value = value
self.parent = self
def update(self, value: T):
self.value = value
return self
def __val__(self):
return self.value
Solution 1:[1]
There is no such thing as a protocol, supporing a generic __val__ method.
You can either cast your class to a comparable type by implementing the respective protocol function, iff applicable, such as __float__, __int__ and compare the casted values via int(obj) <= int(other) instead.
If you need custom functions to compare your objects in other manners, have a look at functools.total_ordering().
Solution 2:[2]
The functools module has a decorator called total_ordering that almost exactly does that for you. You just have to define one of the comparison operators and ideally the __eq__ operator and the rest will be derived from those.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Richard Neumann |
| Solution 2 | Simon Hawe |
