If duck-typing in Python, should you test isinstance?

前端 未结 3 1372
挽巷
挽巷 2021-02-04 05:01

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

3条回答
  •  -上瘾入骨i
    2021-02-04 05:47

    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:

    class Trout(object):
        def __init__(self, value):
            self.value = value
    
        def __eq__(self, other):
            if isinstance(other, Trout):
                return self.value == other.value
            else:
                return NotImplemented
    

    Suppose a RainbowTrout knows how to compare itself to a Trout or to another RainbowTrout, but a Trout only knows how to compare itself to a Trout. In this example, if you test mytrout == myrainbowtrout, Python will first call mytrout.__eq__(myrainbowtrout), notice that it fails, and then call myrainbowtrout.__eq__(mytrout), which succeeds.

提交回复
热议问题