Sub topic 10
Polymorphism and duck typing
This chapter assumes you can define a class with __init__ and instance methods, and that you know how inheritance and method overriding work. Here you will see how Python lets different types be used through one interface.
What polymorphism means
Polymorphism means that code can call the same method on different kinds of objects and get behavior that fits each kind. The caller does not check which class it has. The object decides what the method does.
With inheritance, this works through overriding. A loop can treat a Dog and a generic Animal the same way because both have speak().
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
def chorus(animals):
return [a.speak() for a in animals]
print(chorus([Animal(), Dog(), Cat()])) # ['...', 'Woof', 'Meow']chorus never asks "is this a Dog?". Python looks up speak on each object's own class at call time. This lookup is called dynamic dispatch.
Duck typing
Python does not require a shared parent class. If an object has the method you call, the call works. The saying is: if it walks like a duck and quacks like a duck, treat it as a duck.
class Duck:
def speak(self):
return "Quack"
class Robot:
def speak(self):
return "Beep"
def announce(thing):
print(thing.speak())
announce(Duck()) # Quack
announce(Robot()) # BeepDuck and Robot are unrelated, yet announce accepts both. The "interface" is only the set of attributes the function actually uses.
Built-in protocols
Duck typing is how Python's own syntax works. A for loop accepts anything with __iter__. len() accepts anything with __len__. These sets of methods are called protocols. This is why the special methods from the earlier chapter make your objects feel built-in.
class Playlist:
def __init__(self, songs):
self._songs = list(songs)
def __len__(self):
return len(self._songs)
def __iter__(self):
return iter(self._songs)
p = Playlist(["a", "b", "c"])
print(len(p)) # 3
for song in p:
print(song) # a, b, c
print(sorted(p)) # ['a', 'b', 'c']Playlist is not a list, but len, for, and sorted all work on it.
Common errors
Duck typing moves checks from definition time to call time. Typical problems:
- Missing method. Passing an object without
speakraisesAttributeErroronly when the call runs, possibly deep in your program. - Same name, different meaning. An object may have
close()but not behave the way your code expects. - Type checks that defeat polymorphism. Code like
if type(x) == Dog:breaks for subclasses and for duck-typed objects.
def announce_safe(thing):
try:
return thing.speak()
except AttributeError:
return "(cannot speak)"
print(announce_safe(42)) # (cannot speak)Wrapping every call like this is rarely needed. Usually you let the error surface, or you check at the boundary where untrusted input enters.
Choosing between duck typing and explicit interfaces
Duck typing is flexible and needs little code. Its cost is that nothing enforces the interface until the call happens. When you want that enforcement, for example in a plugin system where others write the classes, use an abstract base class. The next chapters cover that option.
| Approach | Checked when | Needs shared parent | Best for |
|---|---|---|---|
| Duck typing | At call time | No | Small interfaces, flexible code |
| Abstract base class | At instantiation | Yes | Required methods, plugin APIs |
Exercise
A function total_length(items) calls len(item) on each element. Which of these can you pass in: a string, a list, a Playlist as defined above, or the integer 5? Explain why.
Show answer
The string, the list, and the Playlist work, because each defines __len__. The integer 5 raises TypeError because int has no __len__. The function checks no types. It only relies on the __len__ protocol, which is duck typing.
Exercise
Write a class Cow that works with chorus from the first example without inheriting from Animal. What makes it work?
Show answer
class Cow:
def speak(self):
return "Moo"
It works because chorus only calls speak() on each item. Any object with a speak method is accepted, whatever its class.