Chapter 13. Interfaces, Protocols, and ABCs

Program to an interface, not an implementation.

Gamma, Helm, Johnson, Vlissides, First Principle of Object-Oriented Design1

Object-oriented programming is all about interfaces. The best approach to understanding a type in Python is knowing the methods it provides—its interface—as discussed in “Types Are Defined by Supported Operations” (Chapter 8).

Depending on the programming language, we have one or more ways of defining and using interfaces. Since Python 3.8, we have four ways. They are depicted in the Typing Map (Figure 13-1). We can summarize them like this:

Duck typing

Python’s default approach to typing from the beginning. We’ve been studying duck typing since Chapter 1.

Goose typing

The approach supported by abstract base classes (ABCs) since Python 2.6, which relies on runtime checks of objects against ABCs. Goose typing is a major subject in this chapter.

Static typing

The traditional approach of statically-typed languages like C and Java; supported since Python 3.5 by the typing module, and enforced by external type checkers compliant with PEP 484—Type Hints. This is not the theme of this chapter. Most of Chapter 8 and the upcoming Chapter 15 are about static typing.

Static duck typing

An approach made popular by the Go language; supported by subclasses of typing.Protocol—new in Python 3.8—also enforced by external type checkers. We first saw this in “Static Protocols” (Chapter 8).

The Typing Map

The four typing ...

Get Fluent Python, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.