You have a Python class which needs an equals test. Python should use duck-typing but is it (better/more accurate) to include or exclude an isinstance test in the eq function? For example:
class Trout(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
return isinstance(other, Trout) and self.value == other.value
Using isinstance in
__eq__methods is pretty common. The reason for this is that if the__eq__method fails, it can fallback on an__eq__method from another object. Most normal methods are called explicitly, but__eq__is called implicitly, so it requires look-before-you-leap more frequently.EDIT (thanks for the reminder, Sven Marnach):
To make it fallback, you can return the NotImplemented singleton, as in this example:
Suppose a
RainbowTroutknows how to compare itself to aTroutor to anotherRainbowTrout, but aTroutonly knows how to compare itself to aTrout. In this example, if you testmytrout == myrainbowtrout, Python will first callmytrout.__eq__(myrainbowtrout), notice that it fails, and then callmyrainbowtrout.__eq__(mytrout), which succeeds.