☼
⌃
☰

Duck Typing

Table of Contents

"If it walks like a duck and quacks like a duck, it's a duck." An object's suitability for a task is determined by whether it has the required methods and attributes — not by what class or type it explicitly is. Dominant in dynamic languages; Python implements it as the primary approach to polymorphism.

Related: Dynamic Typing Type System Python Type System

Python Examples

PYTHON
# Any object with a .quack() method works here —
# no shared base class or interface required
class Duck:
    def quack(self):
        return "Quack!"

class Person:
    def quack(self):
        return "I'm quacking like a duck!"

class RubberDuck:
    def quack(self):
        return "Squeak!"

def make_it_quack(thing):
    print(thing.quack())   # works for any object with .quack()

make_it_quack(Duck())        # Quack!
make_it_quack(Person())      # I'm quacking like a duck!
make_it_quack(RubberDuck())  # Squeak!

File-like objects

The standard library accepts any object that has .read() and .write() methods — not just actual File objects:

PYTHON
import io
import json

# json.dump() accepts any file-like object
buffer = io.StringIO()           # in-memory string buffer, not a file
json.dump({"key": "value"}, buffer)
content = buffer.getvalue()

# Same function works with a real file, a StringIO, a network socket,
# a gzip file — any object that has .write()

Iteration protocol

for x in thing works on any object implementing __iter__ and __next__ — not just lists or tuples:

PYTHON
class Countdown:
    def __init__(self, n):
        self.n = n

    def __iter__(self):
        return self

    def __next__(self):
        if self.n <= 0:
            raise StopIteration
        self.n -= 1
        return self.n + 1

for n in Countdown(3):
    print(n)   # 3, 2, 1

EAFP vs LBYL

Duck typing pairs naturally with EAFP (Easier to Ask Forgiveness than Permission) — try the operation and handle the failure — rather than LBYL (Look Before You Leap) — check before acting:

PYTHON
# LBYL — check type before using (un-Pythonic)
def process(obj):
    if hasattr(obj, 'read'):
        data = obj.read()

# EAFP — just try it (Pythonic duck typing)
def process(obj):
    try:
        data = obj.read()
    except AttributeError:
        raise TypeError(f"Expected file-like object, got {type(obj)}")

Structural Typing with Protocol (Python 3.8+)

When type hints are needed but inheritance is not, Protocol formalises duck typing statically — the type checker verifies structural compatibility without requiring explicit inheritance:

PYTHON
from typing import Protocol

class Quackable(Protocol):
    def quack(self) -> str: ...

class Duck:
    def quack(self) -> str:
        return "Quack!"

class Person:
    def quack(self) -> str:
        return "I'm quacking!"

def make_quack(thing: Quackable) -> None:
    print(thing.quack())

# Both work — neither inherits from Quackable
make_quack(Duck())
make_quack(Person())

Protocol gives you duck typing with static analysis — the best of both worlds when working in a typed codebase.

Trade-offs

Advantage Disadvantage
Flexible — no inheritance hierarchy needed Runtime errors if expected method is missing
Less coupling between components Harder to understand what interface is expected
Standard library patterns work with custom objects IDE autocomplete less reliable without type hints
Easy to extend third-party code Debugging harder without explicit type contracts

Tips

  • Protocol is the modern solution to the "what does this function actually need?" problem — document implicit duck typing expectations explicitly
  • hasattr() checks are sometimes appropriate but usually signal that EAFP would be cleaner
  • The standard library is built on duck typing — len() calls __len__, for calls __iter__, + calls __add__; implementing these dunder methods integrates custom objects seamlessly