Sub topic 10
Polymorphism and Duck Typing
This chapter assumes you can write a class with __init__ and instance methods, and that you have seen inheritance and super() from earlier chapters. Here you will learn how Python lets one piece of code work with many kinds of objects, and where that approach can fail.
What polymorphism means
Polymorphism means "many shapes". One piece of code calls the same method name on different objects, and each object responds in its own way. The caller does not need to know which kind of object it holds.
You already saw this with Animal and Dog. A loop called speak() on both, and each class supplied its own behavior. That is polymorphism through inheritance and method overriding.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
def chorus(animals):
return [f"{a.name}: {a.speak()}" for a in animals]
print(chorus([Animal("Generic"), Dog("Rex"), Cat("Tom")]))
# ['Generic: ...', 'Rex: Woof', 'Tom: Meow']The function chorus never checks the type of any item. It only relies on each item having a name and a speak() method.
Duck typing
Python goes further than inheritance. The object does not need to share a base class with anything. It only needs to have the methods and attributes the caller uses. This is called duck typing, from the saying "if it walks like a duck and quacks like a duck, it is a duck".
class Robot:
def __init__(self, name):
self.name = name
def speak(self):
return "Beep"
print(chorus([Dog("Rex"), Robot("R2")]))
# ['Rex: Woof', 'R2: Beep']Robot does not inherit from Animal, yet chorus accepts it. Python never checks the class. It looks up name and speak on the object when the code runs, and it raises AttributeError only if one is missing.
Duck typing in the standard library
Duck typing is everywhere in Python. The for loop does not require a list. It requires an object that supports iteration. Any class that defines __iter__ (or __getitem__ with integer indexes) works.
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
print(list(Countdown(3))) # [3, 2, 1]
print(sum(Countdown(4))) # 10Likewise, len() calls __len__, with uses __enter__ and __exit__, and print() of a file-like object only needs a write method. Many functions that take "a file" accept any object with read() or write(), including io.StringIO.
import io
def save_report(lines, out):
for line in lines:
out.write(line + "\n")
buffer = io.StringIO()
save_report(["alpha", "beta"], buffer)
print(buffer.getvalue())
# alpha
# betasave_report works with a real file, a StringIO, or a socket wrapper. That makes it easy to test, because a test can pass a StringIO instead of touching the disk.
The special-method protocols
Special methods from the earlier chapter are the formal side of duck typing. A group of methods that together let an object take part in some behavior is called a protocol. Some common ones:
| Protocol | Methods | Used by |
|---|---|---|
| Iterable | `__iter__` | `for`, `list()`, `sum()` |
| Sized | `__len__` | `len()`, truth tests |
| Container | `__contains__` | `in` |
| Context manager | `__enter__`, `__exit__` | `with` |
| Callable | `__call__` | calling `obj(...)` |
Python looks these methods up on the type of the object, not on the instance. Assigning obj.__len__ = lambda: 3 to one instance does not make len(obj) work. This is a common surprise when people try to patch special methods onto a single object.
Handling a mismatch: EAFP and LBYL
Since Python does not check types in advance, you have two styles for dealing with objects that might not fit.
- LBYL ("look before you leap") checks first, for example with
hasattrorisinstance. - EAFP ("easier to ask forgiveness than permission") just tries the operation and catches the exception.
def describe(thing):
try:
sound = thing.speak()
except AttributeError:
return "this thing cannot speak"
return f"it says {sound}"
print(describe(Dog("Rex"))) # it says Woof
print(describe(42)) # this thing cannot speakEAFP is the usual Python style. It avoids a race between the check and the use, and it supports any object that works, not only those you thought of. It has a pitfall, though. The try block above wraps the whole call to speak(). If speak() itself raised an AttributeError from a bug inside it, you would hide that bug behind the "cannot speak" message. Keep the try block small, or look up the method first:
def describe_safely(thing):
try:
speak = thing.speak
except AttributeError:
return "this thing cannot speak"
return f"it says {speak()}"
print(describe_safely(Dog("Rex"))) # it says WoofNow an error inside speak() propagates normally instead of being mistaken for a missing method.
Polymorphism without inheritance: operators
Operators are polymorphic too. The expression a + b means different things for numbers, strings, and lists, because Python calls a.__add__(b). When the left operand does not know how to handle the right one, it returns NotImplemented. Python then tries the right operand's reflected method, __radd__.
class Money:
def __init__(self, cents):
self.cents = cents
def __repr__(self):
return f"Money({self.cents})"
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented
return Money(self.cents + other.cents)
def __radd__(self, other):
if other == 0: # lets sum() start from 0
return self
return NotImplemented
print(Money(150) + Money(250)) # Money(400)
print(sum([Money(100), Money(200)])) # Money(300)Returning NotImplemented instead of raising an exception is what makes this cooperative. If neither side can handle the operation, Python raises TypeError for you.
Method overriding versus overloading
Some languages let you define several methods with the same name and different parameter types. This is overloading. Python does not do this. A second def with the same name in a class replaces the first one.
class Printer:
def show(self, x):
return f"int {x}"
def show(self, x): # replaces the first show
return f"value {x}"
print(Printer().show(1)) # value 1If you need different behavior by argument type, you have a few choices:
- Use default arguments or
*argsfor different call shapes. - Branch with
isinstanceinside one method, which is acceptable at a boundary but couples the code to specific types. - Use
functools.singledispatchto choose a function by the type of the first argument.
from functools import singledispatch
@singledispatch
def render(value):
return f"object: {value!r}"
@render.register
def _(value: int):
return f"integer: {value}"
@render.register
def _(value: list):
return "list of " + ", ".join(render(v) for v in value)
print(render(5)) # integer: 5
print(render([1, 2])) # list of integer: 1, integer: 2
print(render("hi")) # object: 'hi'Here render is polymorphic over types you did not write, with no changes to those types.
When duck typing goes wrong
Duck typing is flexible, but it has costs you should know about.
- Late errors. A wrong object fails only when the missing method is called, which may be deep in the program or after partial work has been done.
- Matching names with different meanings. A
close()method on a file and aclose()on a sales account are not interchangeable, though both exist. - Unclear contracts. Readers cannot tell which methods a function needs without reading its body.
You can reduce these problems in several ways. Document the methods a function expects. Validate early, at the start of a function, before any side effects. Use type hints with typing.Protocol, which lets a type checker verify duck-typed code without forcing inheritance. For a required interface you control, use an abstract base class, which fails at instantiation time instead of at call time.
from typing import Protocol
class Speaker(Protocol):
name: str
def speak(self) -> str: ...
def announce(s: Speaker) -> str:
return f"{s.name} says {s.speak()}"
print(announce(Robot("R2"))) # R2 says BeepAt runtime Python ignores the Speaker annotation. A checker such as mypy uses it to confirm that Robot has a name and a speak() method, even though Robot never mentions Speaker.
Choosing an approach
| Situation | Good choice |
|---|---|
| Related classes share code and a common base | Inheritance with overriding |
| Unrelated classes that happen to share methods | Duck typing |
| You need to check conformance statically | `typing.Protocol` |
| A required interface you want enforced at instantiation | Abstract base class |
| Behavior varies by argument type for types you don't own | `functools.singledispatch` |
Exercise
A function total(items) calls item.price() on each item and sums the results. A teammate adds a Coupon class with a price() method that does not inherit from Item. Will total accept it? What happens if Coupon only has an attribute price (not a method)?
Show answer
Yes, total accepts Coupon with a price() method, because duck typing only needs the method to exist and be callable, not a shared base class. If price is a plain attribute holding a number, item.price() raises TypeError: 'int' object is not callable (or similar for the stored type), because the lookup succeeds but the value cannot be called. Fix it by making price a method, or by changing total to read item.price and exposing a property on the other classes.
Exercise
Why does Money(5) + 3 raise TypeError in the Money example, instead of returning something or raising AttributeError?
Show answer
Money.__add__ sees that 3 is not a Money and returns NotImplemented. Python then tries int.__radd__(3, Money(5)), which also returns NotImplemented. With both sides declining, Python raises TypeError: unsupported operand type(s).