Recently my colleague Luca got an extracted chapter of Python 3 Object Oriented Programming book to review. As I am a long time Python developer and lover I couldn’t stop myself from taking a look at the chapter so satisfy my curiosity.
A little excerpt from the chapter talks about len, reversed and zip functions illuminated me about the fact that usually due to duck typing Python developers tend to consider sequences and iterables quite the same.
The author of the books says that “The zip function takes two or more sequences and creates a new sequence of tuples” and also the help(zip) documentation says “Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences”.
Indeed the zip function works on every iterable, not just sequences. Python tends to define non-formals protocols and looking around in the doc one can discover that the sequence protocol is defined as implementing __len__() and __getitem__() while the iterable protocol requires to implement __iter__() and return an iterator.
This made me think that having duck typing not only allows easier development of code, but also easier communication of concepts. In any other language commonly using formal protocols (ie interfaces, protocols, or any other formal definition of them) the author of the book would have been required to specify also the definition of the two protocols and the differences between them before the reader would have been actually able to use the zip function. In the Python case the author just had to write the sentence in natural language and the reader is aware that he/she can actually call zip on any collection, container or even generator. Anything that he unconsciously recognizes as a sequence without even having to know the existance of the protocol itself..
Indeed I recognize that duck typing and non-formal protocols tend to be more error prone, but its interesting to notice that they also help to simply communication of concepts as human tend to find easier to feel intuitions over formal definitions.