DEV Community

Cover image for What is Duck typing in Python
prakx1
prakx1

Posted on

What is Duck typing in Python

Duck typing got it's name from Duck test-"If it walks like a duck and it quacks like a duck, then it must be a duck".

In python (and other dynamically typed languages)it doesn't matter what is the type of object what matters is that what it do.

class Elephant:
    def fly(self):
        print("Elephant is flying")


class Duck:
    def fly(self):
        print("Duck is flying")
Enter fullscreen mode Exit fullscreen mode

Take the two objects elephant and duck with same method fly.Let us create a function animal_flying that makes the animal fly.

def animal_flying(animal):
    animal.fly()
animal_flying(Duck())
animal_flying(Elephant())
Enter fullscreen mode Exit fullscreen mode

[Output]:

Elephant is flying
Duck is flying
Enter fullscreen mode Exit fullscreen mode

The function makes both duck and elephant fly without checking there type as both have the fly method, and this feature of using a object depending upon the methods it has irrespective of its type is called Duck typing.

Top comments (4)

Collapse
 
michaelcurrin profile image
Michael Currin

Maybe it can be shorter at the end as using a function like animal_flying just to create an object and throw it away is not good practice and makes the code harder to follow as tutorial

Duck().fly()
Elephant.fly()
Enter fullscreen mode Exit fullscreen mode

Or

e = Elephant()
e.fly()
d = Duck()
d.fly()
Enter fullscreen mode Exit fullscreen mode
Collapse
 
michaelcurrin profile image
Michael Currin • Edited

Clear example.

A good case for using that flow is when you have one class with a lot of if/else statements in a method. Rather break out into multiple classes and each as a method like .fly() that does the appropriate thing without checking what the type is. That is polymorphism.

Duck typing relates to the "Tell, don't ask" philosophy. Instead of checking what the type is and changing behavior based on type, just tell the object to fly and it will know what to do.

Collapse
 
prakx1 profile image
prakx1

Thanks.

Collapse
 
pomfrit123 profile image
***

Good to know