Sub topic 2
Duck typing and where it falls short
This chapter assumes you can write Python functions and classes, and that you know basic type hints. It also assumes you know what a static type checker such as mypy or pyright does: it reads your code without running it and reports type errors. The previous chapter covered subtyping by declaration (nominal subtyping), where a class counts as a subtype only if it names its parent. Here you will look at the other common style in Python, duck typing. You will see what it gives you and the specific ways it fails, because those failures are the reason protocols exist.
What duck typing means
Duck typing is a style where a function does not care what class an object has. It only cares that the object supports the operations the function performs. The name comes from the saying "if it walks like a duck and quacks like a duck, it is a duck."
Python's runtime works this way by default. When you write speaker.speak(), the interpreter looks up the attribute speak on the object and calls it. It does not check the object's class against any list. If the lookup succeeds, the call proceeds.
class Duck:
def speak(self) -> str:
return "Quack"
class Robot:
def speak(self) -> str:
return "Beep"
def announce(speaker) -> None:
# No type information: any object with .speak() works at runtime,
# and a wrong argument only fails when the line executes.
print(speaker.speak())
announce(Duck())
announce(Robot())
try:
announce(42)
except AttributeError as error:
print(f"Failed at runtime: {error}")Running this prints Quack, Beep, and then Failed at runtime: 'int' object has no attribute 'speak'.
Duck and Robot share no parent class. Both work because both have a speak method that takes no arguments. This is why Python code is easy to extend: a new class works with announce the moment it grows a speak method, with no registration and no inheritance.
Why people like it
Duck typing has real advantages, and any replacement has to keep them.
- Decoupling. A library author does not need to know about your class, and your class does not need to import the library's base class.
- Less ceremony. You do not write a hierarchy just to pass an object to a function.
- Easy test doubles. A small fake object with the right methods can stand in for a database or network client.
- Works with existing code. You can pass objects from third-party packages that were written without knowing about your function.
The cost appears when you ask: how does anyone know what announce expects?
Where it falls short
The contract is invisible
Look at the signature def announce(speaker) -> None. The parameter speaker has no annotation. A reader has to read the body to learn that it needs a speak method. A body of three lines is easy to read. A function that touches speaker in twelve places across several helper functions is not.
The contract still exists. It is just written nowhere. It lives in the code's behavior and in the author's head.
Failures happen late
A static type checker cannot reject announce(42) here, because speaker has no declared type and the checker has nothing to compare against. The error appears only when the line runs. If that line sits in a rarely used branch, the bug can ship and sit unnoticed for months.
Failures can happen halfway through
A mistake does not always fail at the first call. Consider a function that processes a list:
class Duck:
def speak(self) -> str:
return "Quack"
class Robot:
def speak(self) -> str:
return "Beep"
def announce_all(speakers) -> None:
for speaker in speakers:
print(speaker.speak())
try:
announce_all([Duck(), Robot(), 42])
except AttributeError as error:
print(f"Stopped: {error}")The output is Quack, Beep, then Stopped: 'int' object has no attribute 'speak'. Two items were already handled when the third failed. If those first two had written to a database or sent an email, you would now have a half-finished job. A check done before the loop would have prevented that, but plain duck typing gives you no such check.
Close is not the same as compatible
Having an attribute with the right name does not mean the object fits. Three kinds of near miss pass a naive "has the attribute" test and still break the caller:
class Cat:
def speak(self, volume: int) -> str: # extra required parameter
return "Meow" * volume
class Dog:
def speak(self) -> None: # prints instead of returning text
print("Woof")
class Parrot:
def speek(self) -> str: # misspelled name
return "Hello"
def announce(speaker) -> None:
print(speaker.speak())
for animal in (Cat(), Dog(), Parrot()):
try:
announce(animal)
except (TypeError, AttributeError) as error:
print(f"{type(animal).__name__}: {type(error).__name__}: {error}")Catfails with aTypeErrorbecausespeak()is missing the required argumentvolume.Dogdoes not fail on the call. It printsWoof, returnsNone, and thenannounceprintsNone. The bug is silent.Parrotfails with anAttributeError, and the namespeekis a typo no one has to notice until the call.
The silent Dog case is the most dangerous. A wrong return value can flow onward through the program and cause a failure far from its cause.
Tools cannot help you
Because the expected shape is not written down, editors cannot autocomplete speaker. and a rename of speak cannot find every caller that depends on it. Refactoring means searching for strings and hoping.
The timing of each failure
The diagram shows when each kind of mistake is caught, depending on whether the expected shape is declared.
The usual workarounds and their costs
Python programmers have long defended against these problems. Each defense has a price.
Look before you leap
def announce(speaker) -> None:
if not hasattr(speaker, "speak"):
raise TypeError(f"expected an object with speak(), got {type(speaker).__name__}")
print(speaker.speak())This fails earlier and with a clearer message. But it checks only that the name exists. Cat and Dog from above would still pass it. It also adds code to every function that wants the check, and the check is still a runtime check.
Easier to ask forgiveness
def announce(speaker) -> None:
try:
text = speaker.speak()
except AttributeError:
text = "<cannot speak>"
print(text)This style (Python programmers call it EAFP) is idiomatic, but it has a trap. The except AttributeError also catches an AttributeError raised from inside a correct speak method, for example from a bug in its own body. The real error is then hidden behind your fallback.
Inheritance from a common base
You can make every speaker inherit from an abstract base class and check with isinstance. That gives you a declared contract, but it gives up the main benefit of duck typing. Classes you do not control, such as those from a third-party library, cannot be made to inherit from your base. The final chapters compare this approach with protocols in detail.
Documentation
A docstring that says "speaker must have a speak() method returning str" helps humans. No tool checks it, and it drifts out of date.
What we actually want
The list of failures points to a wish list:
- Keep the freedom of duck typing: unrelated classes work with no shared parent.
- Write the expected shape down in the signature, so readers and editors can see it.
- Have a static type checker verify, before the program runs, that every argument has that shape, including parameters and return types.
Item 1 is what makes duck typing pleasant. Items 2 and 3 are what it lacks. Nominal subtyping gives you 2 and 3 but not 1. The next chapters introduce structural subtyping, where compatibility is decided by an object's shape instead of its declared ancestry. typing.Protocol is how you write that shape down.
Summary
- Duck typing means a function uses whatever operations it needs and accepts any object that supports them.
- It keeps code decoupled and flexible.
- Its contract is unwritten, so readers must read the body to learn it.
- Mistakes surface only when the line runs, which can be late and can leave work half done.
- Objects with the right name but the wrong parameters or return type can fail loudly, or worse, silently.
hasattr,try/except AttributeError, and shared base classes each fix part of the problem and add a cost.- What is missing is a way to declare the expected shape and have a type checker verify it without requiring inheritance.
Exercise
In the Dog class above, speak prints "Woof" and returns None. Why is this a worse outcome for the caller than the Parrot class with the misspelled speek method, and would hasattr(speaker, "speak") catch either one?
Show answer
Parrot fails immediately with an AttributeError, so the mistake is loud and points at the cause. Dog does not fail at all: announce prints None, and the wrong value can travel on through the program and cause a confusing error elsewhere. hasattr(speaker, "speak") catches Parrot, because the name speak does not exist on it, but it does not catch Dog, because Dog has a method named speak. The check looks at the name only, not at the return type.
Exercise
A function save_all(stores) loops over a list and calls store.write(data) on each one. The third item in the list has no write method. Describe what state the program is left in, and name one change that would detect the problem before any write happens.
Show answer
The first two stores have already written their data when the third raises an AttributeError, so the operation is half finished and the data may be inconsistent across stores. One fix is to validate every item before the loop starts, for example with hasattr on each store. A stronger fix is to annotate the parameter with a declared shape so that a static type checker rejects the bad list before the program runs.
Exercise
Why does catching AttributeError around speaker.speak() risk hiding real bugs?
Show answer
The try block cannot tell where the AttributeError came from. If speak exists but its own body raises an AttributeError, for example by using a misspelled attribute, the except clause catches that too and runs the fallback. The real bug is then hidden.