I'm implementing my own class, with custom __eq__
. And I'd like to return True
for things that are not "equal" in a mathematical sense, but "match" in a fuzzy way.
An issue with this is, however, that this leads to loss of transitivity in a mathematical sense, i.e. a == b && b ==c
, while a
may not be equal to c
.
Question: is Python dependent on __eq__
being transitive? Will what I'm trying to do break things, or is it possible to do this as long as I'm careful myself not to assume transitivity?
Use case
I want to match telephone numbers with one another, while those may be either formatted internationally, or just for domestic use (without a country code specified). If there's no country code specified, I'd like a number to be equal to a number with one, but if it is specified, it should only be equal to numbers with the same country-code, or without one.
So:
- Of course,
+31 6 12345678
should equal+31 6 12345678
, and06 12345678
should equal06 12345678
+31 6 12345678
should equal06 12345678
(and v.v.)+49 6 12345678
should equal06 12345678
(and v.v.)- But
+31 6 12345678
should not be equal to+49 6 12345678
Edit: I don't have a need for hashing (and so won't implement it), so that at least makes life easier.
a == b == c
may be true buta == c
may be false, then you'll need to be very careful with your conditionals.a == b
just calls your functiona.__eq__(b)
. As other commentators pointed out, you can define that however you want, but you have to live with the consequences. Personally, I wouldn't go down the__eq__
route, but define another method likefuzzy_match
, especially since__eq__
in terms of string equality might still be useful in your case.