Chapter 2: Polymorphism

Real examples of duck typing

face Josiah Wang

One good example of duck typing in the Python Standard Library is an iterable. You have seen iterables in action: list, range, tuple, dict, enumerate, generator, a file pointer, etc. What these classes have in common is that they all implement the __iter__() method (that returns an iterator). You can pass any of these to the all() function, and it will work since that’s all all() really needs.

To qualify as an iterator, an object must also implement the __next__() method, in addition to __iter()__. This will allow it to be used as part of a for-loop. At each iteration of the loop, Python will invoke __next__() to obtain the next item in the iterator.

Duck typing in scikit-learn

If you have used the scikit-learn machine learning library, you can observe the same thing: to be an estimator, a class must implement fit(). To be a predictor, it must implement predict(). All transformers must implement transform(), while all models must implement score(). There is no need to subclass anything.

Duck typing vs. Java/C++ interfaces

If you come from a Java/C++ background, then this might be a paradigm shift for you. There is no need to use Interfaces since Python is a dynamically typed language!