DEV Community

Cover image for What is duck typing?
icncsx
icncsx

Posted on

5 2

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(): 
    obj.fly() 
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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (3)

Collapse
 
spic profile image
Sascha Picard • Edited

I know this concept as "structural typing", see isthisit.nz/posts/2020/typescript-...

Collapse
 
kickbuttowski80 profile image
Izak T

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

Collapse
 
arvindpdmn profile image
Arvind Padmanabhan

It's a useful topic to learn. Those who like to know more can visit devopedia.org/duck-typing

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay