Duck Typing: Let the ducks quack!

Anshul vyas
Sep 6, 2018 · 2 min read

Duck typing is a concept that says that the “type” of the object is a matter of concern only at runtime and you don’t need to explicitly mention the type of the object before you perform any kind of operation on that object, unlike normal typing where the suitability of an object is determined by its type. The name comes from the phrase

“If it looks like a duck and quacks like a duck, it’s a duck”.

Conceptually, all this means is that things that quack appropriately should be treated that way instead of directly examining the actual class/type of an object to determine its ability to quack.

The Following Example will help us clear the concept:

class Duck:
def quack():
print('Quack!')
class Goose:
def quack():
print('Quack')
Goose().quack()
>> Quack!
Duck().quack()
>> Quack!

Despite not being defined as a subtype/subclass of Duck, Goose still quack in the way you would expect a duck to do. So, here the type of object is not the concern when invoking the quack() on the objects of the different classes. The concern is the behaviour. If a particular behaviour is present in the class then it will get invoked no matter what type of object invokes it. The resolution here is based on the signature of the functions, not the type of object invoking it. By extension, If I access a property on this object and it returns something back to me, then I can assume it has this property.

In absence of duck typing, you have to probably go through the route of inheritance and have the goose extend the duck in order to have a quack behaviour defined for it.

Duck typing is property specific to dynamic languages like python, ruby. It comes as a side effect of dynamic languages and it is interesting what it can bring in terms of conciseness and low-coupling to the system design and architecture.