Duck typing
Duck typing means Python cares about what an object can do, not what class it came from. If it has the methods your code calls, it is an acceptable argument, regardless of its type or ancestry.
Detailed Explanation
The name comes from the saying: if it walks like a duck and quacks like a duck, treat it as a duck. Applied to code, it means a function should ask "does this object support the operation I need?" instead of "is this object an instance of the type I had in mind?".
Compare it to the nominal typing you find in Java or C#. There, an object can only be passed where an Appendable is expected if its class explicitly declares implements Appendable. The relationship is by name, and it has to be written down in advance. In Python the relationship is by shape, and nobody has to declare anything. A class that defines write(self, text) is already usable everywhere a writable target is expected, even if its author never heard of the function consuming it.
This is not a loophole. It is how the standard library is built. The protocols you already use are duck-typed method contracts:
| Protocol | Method you define | What it unlocks |
|---|---|---|
| Iterable | __iter__ | for, list(), sum(), unpacking |
| Sized | __len__ | len(), plus truthiness for free |
| Container | __contains__ | the in operator |
| Context manager | __enter__, __exit__ | the with statement |
| Callable | __call__ | obj() syntax, so instances act like functions |
Define __len__ and __iter__ on your own class and len(bag), for item in bag, and sum(bag) all start working. No inheritance was involved.
Duck typing also shapes Python's error style. The idiomatic approach is EAFP, "easier to ask forgiveness than permission": attempt the operation and handle the exception. The alternative, LBYL, "look before you leap", checks with hasattr or isinstance first. EAFP is preferred because the check and the use can disagree, and because a wall of hasattr calls documents nothing useful. Wrap the call in try/except AttributeError or except TypeError and let objects that genuinely work, work.
Reach for duck typing whenever you want a seam. Writing a report exporter that takes any object with .write() means you can pass a real file, an io.StringIO buffer in a unit test, a gzip stream, or an S3 upload wrapper, with no changes and no base class. That single idea removes most of the need for dependency-injection frameworks in Python.
The cost is that a broken assumption surfaces late and unhelpfully. Pass an object that has .write() but not .flush() and you learn about it as an AttributeError three frames deep, possibly after writing half a file. There is also no signature enforcement: a method with the right name and the wrong parameters satisfies the duck test and fails at the call.
typing.Protocol from PEP 544 is the modern middle ground. You describe the shape once, and a static type checker verifies every call site without any class inheriting from it. Runtime behaviour is unchanged, so you keep the flexibility. Adding @runtime_checkable lets isinstance work against the protocol, but understand its limit: it checks only that the attribute names exist, never that the signatures match.
Code Examples
import io
def write_report(destination, rows):
"""Accepts anything with a .write() method. That is the entire contract."""
destination.write("id,total\n")
for row in rows:
destination.write(f"{row['id']},{row['total']}\n")
orders = [{"id": 1, "total": 250}, {"id": 2, "total": 99}]
# A real file works.
with open("report.csv", "w") as handle:
write_report(handle, orders)
# An in-memory buffer works, which is how you test this without the disk.
buffer = io.StringIO()
write_report(buffer, orders)
print(buffer.getvalue().splitlines()[0]) # id,total
# So does a class that knows nothing about files.
class UppercaseSink:
def __init__(self):
self.lines = []
def write(self, text): # the only method the contract needs
self.lines.append(text.upper())
sink = UppercaseSink()
write_report(sink, orders)
print(sink.lines[0].strip()) # ID,TOTALfrom collections.abc import Iterable, Sized
class Cart:
"""Implementing two dunder methods opts this class into two protocols."""
def __init__(self, items):
self._items = list(items)
def __iter__(self):
return iter(self._items) # unlocks for, list(), sum()
def __len__(self):
return len(self._items) # unlocks len() and truthiness
cart = Cart([19.99, 5.00])
print(len(cart), sum(cart)) # 2 24.99
print(bool(Cart([]))) # False -> empty means falsy, via __len__
# Cart never inherited from anything, yet the ABCs recognise it,
# because these ABCs check for the methods rather than the ancestry.
print(isinstance(cart, Iterable), isinstance(cart, Sized)) # True True
# EAFP: try the operation instead of interrogating the object first.
def total_of(value):
try:
return sum(value)
except TypeError: # not iterable, or holds non-numbers
return value
print(total_of(cart), total_of(7)) # 24.99 7from typing import Protocol, runtime_checkable
@runtime_checkable
class Cache(Protocol):
"""Describes a shape. No class needs to inherit from it."""
def get(self, key: str) -> str | None: ...
def set(self, key: str, value: str) -> None: ...
class DictCache: # note: does NOT subclass Cache
def __init__(self):
self._data = {}
def get(self, key):
return self._data.get(key)
def set(self, key, value):
self._data[key] = value
def remember(cache: Cache, key: str, value: str) -> str:
cache.set(key, value) # mypy verifies DictCache fits here
return cache.get(key) or ""
print(remember(DictCache(), "user:1", "ana")) # ana
print(isinstance(DictCache(), Cache)) # True
class BadCache:
def get(self): ... # wrong signature
def set(self): ...
# isinstance only looks for attribute NAMES, so this passes at runtime
# while a static checker rejects it.
print(isinstance(BadCache(), Cache)) # TrueCommon Gotchas
A missing method fails mid-operation
`write_report` that calls `.write()` twice and `.flush()` once can leave a half-written file when the third call is missing. Validate at the boundary, or use a `Protocol` plus a type checker so mismatches are caught before deployment.
`@runtime_checkable` checks names, not signatures
`isinstance(obj, MyProtocol)` returns `True` for an object whose methods take the wrong arguments, and it ignores non-method attributes entirely. Treat it as a weak smoke test, never as validation.
Strings are iterable, so they sneak into container code
a function that loops over its argument will happily iterate `"abc"` one character at a time when the caller meant one name. Check `isinstance(value, str)` explicitly before treating an argument as a collection.
Duck typing makes mocking trivial, which can hide interface drift
a hand-written fake with two methods keeps passing after the real class grows a third. `unittest.mock.create_autospec` ties the fake to the real signature.