Skip to main content

Duck Typing

About

Origin of the name

"If it walks like a duck and it quacks like a duck, then it must be a duck"

Duck Typing is a type system used in dynamic languages, and it is a core concept in Python. With duck typing, type or the class of an object is less important that the method it defines, so we do not check types at all. Instead, we check for the presence of a given method or attribute.

Key Principles

  • Behaviour over type

    We care about what an object can do, not what it is

  • No need for explicit interfaces

    Unlike statically-typed languages like Java or C++, Pyton doesn’t require explicit interfaces or type declarations (can be seen in example below)

  • Flexibility

    Duck typing makes Python highly dynamic and flexible, allowing you to write generic code that can operate on different kinds of objects as long as they implement the expected methods

Example

class Duck:
def swim(self):
print("Swim!")

class Person:
def swim(self):
print("I'm swimming like a duck!")

def make_it_swim(entity):
entity.swim()

duck = Duck()
person = Person()

# Both objects can be passed because they implement quack() and swim()
make_it_swim(duck) # Swim!
make_it_swim(person) # I'm swimming like a duck!

Here, the function make_it_swim doesn’t care if the object is a Duck or a Person, as long as it has the swim method

Pros

  • Polymorphism
  • Code reusability
  • Less Boilerplate

Cons

  • Runtime errors
  • Readability Issues
  • Less explicit contract

Use Cases

  • Polymorphism
  • Dynamic method calls