Duck Typing in python

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:

Quacked
Louder Quack
Traceback (most recent call last):
File "/Users/gaurav/personal/development/grasp-python/base/advanced/duck_typing.py", line 33, in <module>
MakeItQuack(Eagle())
File "/Users/gaurav/personal/development/grasp-python/base/advanced/duck_typing.py", line 29, in __init__
bird.quack()
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

One thought on “Duck Typing in python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s