Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Tuesday, April 12, 2011

Duck-typing in practice

As a recent Python devotee, I have found that duck-typing can sometimes be harder in practice than in theory. In theory, if it looks like a duck, swims like a duck, and quacks like a duck, then it's a duck. In practice, or at least in my practice, there are ducks incapable of flight. Or wolves in ducks' clothing. All attempted humor aside, there is difficulty in reconciling a type-based view of object oriented programming and the much more laissez-faire approach that Python adopts.

It should be obvious that duck-typing provides a more variable approach to implementation, something which was included in the driving factors behind the invention of OOP. Nonetheless, #python on freenode is inundated with questions from inexperienced programmers as to the proper way to distinguish a list from a string, or other similar situations. I will side with the operators of #python and assert that the correct way doesn't happen to be isinstance(). This function's usage is contrary to the idea of duck-typing and, in its positive form, should be avoided at all costs. However, how does one distinguish a list from a string?

On the surface, there are many similarities between these two datatypes. Both possess a length, have __add__ ,__mul__ , and  __contains__ methods. One example of a method they don't share is the append method.

What I am getting to is that, while duck-typing ensures that a function, or bit of code will work regardless of type, so long as it has the proper interface, what happens when two things share the relevant methods and the only thing distinguishing them is irrelevant to the problem at hand? It is easy to dismiss these situations as inconsequential given the nature of duck-typing (if they share the relevant interface, then it SHOULD work). But is it possible to make concessions? Is duck-typing compatible with negative definition by type (a set of "is not isinstance()" checks)? After all, if something looks like a duck, swims like a duck, and quacks like a duck, can we at least check to make sure it isn't a wolf in duck's clothing?

If the number of question marks in this post are any indication, I invite discussion on this topic, perhaps someone more knowledgeable than me will have more declarative sentences.