Python: Raise error when comparing objects of different type for equality

As far as I understand, in Python, comparing the instances of two different classes for equality, does:

  • evaluate the __eq__ method of the first instance and return the result
  • Except if the result is NotImplemented, then evaluate the __eq__ method of the second instance and return the result
  • Except if the result is NotImplemented, then compare for object identity and return the result (which is False)

I encountered multiple times situations where a raised Exception would have helped me to spot a bug in my code. Martijn Pieters has sketched in this post a way to do that, but also mentioned that it's unpythonic.

Besides being unpythonic, are there actual problems arising from this approach?


Solution 1:

Strictly speaking, it is, of course, "unpythonic" because Python encourages duck typing alongside strict subtyping. But I personally prefer strictly typed interfaces, so I throw TypeErrors. Never had any issues, but I can't difinitively say that you will never have any.

Theoretically, I can imagine it being a problem if you find yourself in need to use a mixed-type container like list[Optional[YourType]] and then compare its elements, maybe indirectly, like in constructing set(your_mixed_list).