less than 1 minute read

Quite simply put, Duck typing gives a programmer the ability to not worry about the type of a class rather perform the required operations.

Let’s take a simple code example as below:

If we execute this code:

Louder Quack
Traceback (most recent call last):
  File "/Users/gaurav/personal/development/grasp-python/base/advanced/duck_typing.py", line 33, in <module>
  File "/Users/gaurav/personal/development/grasp-python/base/advanced/duck_typing.py", line 29, in __init__
AttributeError: 'Eagle' object has no attribute 'quack'

Observe here we are passing an object bird to MakeItQuack class constructor and invoking quack() on the passed object.

Thus classes which have an implementation of quack method will be able to call (Duck, AnotherDuck objects) whereas we get a AttributeError if we try to pass an object which does not provide an implementation of quack() ,herethe Eagle class.

This is the essence of duck typing. Having the ability to do this without writing an Interface is really awesome.

In case you want to know more, you can further read voidspace blog on the same topic