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

前端 未结 3 1371
挽巷
挽巷 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条回答
  •  别那么骄傲
    2021-02-04 05:32

    The "duck-typing" principle is that you don't care what other is, as long as it has a value attribute. So unless your attributes share names with conflicting semantics, I'd suggest doing it like this:

    def __eq__(self, other):
        try:
            return self.value == other.value
        except AttributeError:
            return False # or whatever
    

    (Alternately you could test whether other has a value attribute, but "it's easier to ask forgiveness than to get permission")

提交回复
热议问题