How to handle “duck typing” in Python?

前端 未结 5 825
生来不讨喜
生来不讨喜 2020-12-08 07:46

I usually want to keep my code as generic as possible. I\'m currently writing a simple library and being able to use different types with my library feels extra important th

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 08:15

    Good question, and quite open-ended. I believe typical Python style is not to check, either with isinstance or catching individual exceptions. Cerainly, using isinstance is quite bad style, as it defeats the whole point of duck typing (though using isinstance on primitives can be OK -- be sure to check for both int and long for integer inputs, and check for basestring for strings (base class of str and unicode). If you do check, you hould raise a TypeError.

    Not checking is generally OK, as it typically raises either a TypeError or AttributeError anyway, which is what you want. (Though it can delay those errors making client code hard to debug).

    The reason you see TypeErrors is that primitive code raises it, effectively because it does an isinstance. The for loop is hard-coded to raise a TypeError if something is not iterable.

提交回复
热议问题