DISQUS

Dobesland: Python isinstance considered useful | Dobesland

  • paddy3118 · 2 years ago
    Maybe some of your problem with duck typing as it is called is reflected in your first paragraph:

    " You should instead infer what type of object you have by checking for the presence or absence of particular methods".

    That isn't quite right. You should just go ahead and use whatever object you have assuming it is the correct object and trust Pythons run-time type checking and your programming team to "do the right thing". It isn't that explicit interface checking isn't needed in Python - its just not the only way, or necessarily the first way to try when programming Python.

    - Paddy.

    Ref: http://en.wikipedia.org/wiki/Duck_typing
  • dobes · 2 years ago
    I am aware of that - in the beginning of the last paragraph I wrote "When designing an API, the majority of the functions’ parameters will expect only one type of argument, and if you like the idea of flexibility, just don’t assert against the parameters at all - let the app fail when it discovers a needed operation is missing. That’ll allow callers to use subclassing or not, as they choose."

    The main point of the article is not to decry duck typing, but instead to defend isinstance() as something which is not harmful, but useful.

    I've heard the argument that checking the types of things shows a problem with the design of your code, and you should never use hasattr or isinstance. Maybe so - but most of the suggested solutions wouldn't work for objects I didn't create, or require a lot of extra unnecessary code.

    Recently I've been introduced into PyProtocols, which seems to provide an elegant solution to the problems with both interfaces (hard to adapt other people's object to an interface) and duck typing (fragility in the face of changes).