Sub topic 2
Duck typing and where it falls short
Prerequisites
This chapter assumes you can write Python functions and classes and read basic type hints. It also assumes you know that a static type checker such as mypy or pyright analyses your code without running it.
The idea behind duck typing
Duck typing comes from the saying "if it walks like a duck and quacks like a duck, it is a duck." Python does not check what class an object belongs to. It tries the operation you wrote, and the operation either works or raises an error.
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.
print(speaker.speak())
announce(Duck())
announce(Robot())
try:
announce(42)
except AttributeError as error:
print(f"Failed: {error}")Duck and Robot share no base class. announce accepts both because both have a speak method. The call with 42 fails only when speaker.speak() executes.
What duck typing gives you
- No forced inheritance. A class from another library works with your function if it has the right methods.
- Easy test doubles. A small fake object with one method can stand in for a large real one.
- Less ceremony. You write the operation you need instead of declaring a hierarchy first.
Where it falls short
The signature announce(speaker) hides a requirement. The requirement exists, but only the function body states it.
- The contract is invisible. A reader must read the body to learn that
speakerneeds aspeakmethod. If the function grows, the requirement list grows with it, and you have to scan the whole body to find it. - Errors arrive late. A wrong argument fails only when the line runs. If the call sits in a rarely used branch, the bug can reach production unnoticed.
- Tools cannot help. A type checker has no declared shape to compare against, so it cannot warn about
announce(42). Editors cannot offer completion onspeaker.. - Partial matches slip through. Having a method with the right name is not enough. The signature must also fit the call.
The fourth point is easy to miss:
class Cat:
def speak(self, volume: int) -> str:
return "Meow" * volume
def announce(speaker) -> None:
print(speaker.speak())
try:
announce(Cat())
except TypeError as error:
print(f"Failed: {error}")Cat has a speak method, so it looks like a duck. The call fails because speak requires an argument that announce does not pass.
Every failure branch in the diagram happens while the program is running. Nothing is checked beforehand.
The dilemma
You can add a type hint to improve things, but the obvious choices both have a cost.
- Annotating
speaker: Ducklets the checker catchannounce(42). It also rejectsRobot, even thoughRobotworks fine at runtime. - Making
DuckandRobotinherit from a sharedSpeakerbase class fixes the checker. It also forces every speaker, including classes you do not control, to inherit from your class.
Python's answer is structural subtyping, which the next chapter introduces. A class counts as compatible when it has the right shape, with no inheritance needed. Protocols let you write that shape down so a type checker can verify it.
Exercise
A function save(target) calls target.write(data). A teammate passes an object whose write method requires two positional arguments. Name two reasons this problem is not caught before the program runs, and say what the failure looks like at runtime.
Show answer
First, target has no annotation, so a type checker has no declared shape to compare the argument against. Second, Python checks only when the line executes, and the object does have a write attribute, so nothing looks wrong until the call itself. At runtime the call raises a TypeError because the required second argument is missing. It is not an AttributeError, since the method exists but its signature does not fit the call.