Function Interfaces in Python

PYTHON PROGRAMMING

Function interfaces in Python can be implemented using type hints and protocols.

18 min read

4 hours ago

Photo by Rubaitul Azad on Unsplash

While Python doesn’t offer interfaces in the sense commonly known from other programming languages, it does offer similar functionalities. Traditional ones are abstract base classes (ABCs), available via the abc module. Later on, type hints and typing protocols (typing.Protocol) were added.

Abstract base classes (ABCs) and typing protocols serve as Python’s mechanisms for defining expected structures and behaviors of classes, similar to interfaces in other programming languages. Although Python itself doesn’t formally use the term “interface” to describe this functionality, the concept is closely in line of what Python “protocols” offer. In fact, the term “protocol” had been used in Python to describe interfaces well before typing.Protocol was added to the typing module. Therefore, Python’s dynamic nature allows for the creation of dynamic interfaces, while type hints and typing protocols facilitate the specification of interfaces from a static-checking perspective. We will discuss this in this article.

Abstract base classes and typing protocols are typically considered in the context of creating custom classes: you can create an abstract base class or a protocol when you need the user to implement a class with some expected structure and behavior. While ABCs work with classes only, typing protocols offer something that ABCs don’t: function interfaces.

Python originally didn’t offer dedicated tools for creating function interfaces. This changed with the addition of type hints, and now we can create function interfaces in two ways: via type hints and typing protocols.

Python type hints enable one to specify the expected types of function parameters and return values. And what does a function interface specify? Does it not specify the expected types of function parameters and return values? This is why a function’s signature with type hints can be considered a form of function interface.

Python type hints do not directly provide the same level of interface specification for classes as they do for functions, so they don’t work in the same way for classes and…