liveBook · Manning

Duck typing

As explained in Practices of the Python Pro

Duck typing is a typing approach that determines an object's suitability by the presence of the required behavior rather than by its declared class or type.

Duck typing judges an object by whether it provides the behavior a caller needs, not by its declared class. Python checks the method call at runtime and raises AttributeError when the behavior is missing. section 3.5

The idea follows the familiar duck test: if something walks and quacks like a duck, treat it as a duck. This supports polymorphism while avoiding rigid inheritance hierarchies. section 3.5

A swappable tire

A Bicycle need not know a tire’s class. Any tire-like object can be substituted when it supplies the expected information and behavior, such as a FancyTire. Likewise, command objects can vary internally as long as they provide execute for the presentation layer. section 7.2.2

How Practices of the Python Pro covers it

How deep it goes
Explains runtime method checks and shared interfaces, but stops short of formal interface enforcement.
Examples
Uses the duck analogy, FancyTire substitution, and command objects sharing execute.
What you can do after
Apply it via Python by designing consumers around expected methods and attributes rather than concrete classes.
How it connects
Connects dynamic typing, polymorphism, composition, inheritance, and interfaces.

Also explained in

Compare how 3 books explain duck typing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.