3 ms·
I don't trust someone who can't implement `__cmp__` to implement `__lt__` either.
by ioquatix 7y ago
I don't trust someone who can't implement `__cmp__` to implement `__lt__` either.
- masklinn 7y agoExperience says you're way wrong, simply because combining a sequence of sub-lt calls is way simpler and shorter than combining a sequence of cmp: def __lt__(self, other): return self.a < other.a and self.b < other.b and self.c < other.c meanwhile def __cmp__(self, other): v = cmp(self.a, other.a) if v != 0: return v v = cmp(self.b, other.b) if v != 0: return v v = cmp(self.c, other.c) if v != 0: return v return 0 Rust (for instance) makes the latter less offensive (and error-prone) by providing built-in combinators: https://doc.rust-lang.org/std/cmp/enum.Ordering.html https://doc.rust-lang.org/std/cmp/enum.Ordering.html impl Ord for Thing { fn cmp(&self, other: &Self) -> Ordering { self.a.cmp(&self.a) .then(self.b.cmp(&other.b)) .then(self.c.cmp(&other.c)) } }
- BlackFingolfin 7y agoBut that first comparison function is usually not what you want, you want lexicographic ordering. This very example is in fact discussed in the article, as an example to how people often mess this up...
- masklinn 7y ago> But that first comparison function is usually not what you want All those functions implement the same comparison, the first is simply not including the similarly trivial implementation for eq: def __eq__(self, other): return self.a == other.a and self.b == other.b and self.c == other.c > you want lexicographic ordering Every word here makes sense but the objection makes none. What are you trying to say exactly?