DEV Community

Cover image for What is duck typing?

Posted on

What is duck typing?

Duck Typing

The phrase originates from the saying: "If it walks like a duck, swims like a duck, quacks like a duck, then it probably is a duck." Cool saying, but what does this mean?

In practice, what this means is that as programmers, we can focus on the expected behaviour of an object. Even if a Person object isn't a Duck object, if a Person object has a "quack" method, it can quack. Simple as that.

class Duck: 
    def quack(self): 
        print("I can quack because I am a duck.") 

class Person:
    def quack(self): 
        print("I can quack because it's defined.")

# Attributes having the same behaviour suggest duck typing
for obj in Duck(), Person(): 
Enter fullscreen mode Exit fullscreen mode

In summary, duck typing focuses on an object's behaviour (method) - not type. It does not matter whether a person is actually a Duck or a Person. As long as I want that person to call the quack method and it can, we're good. That's why it is called duck typing: if it looks like a duck (e.g., it has a method called quack) then who cares if it's a duck or a person. As long as I can call the method I want to call on that object, I'm good.

Top comments (3)

spic profile image
Sascha Picard • Edited

I know this concept as "structural typing", see

kickbuttowski80 profile image
Izak T

It feels it needs more info to explain the concept fully?

arvindpdmn profile image
Arvind Padmanabhan

It's a useful topic to learn. Those who like to know more can visit