Interfaces

An interface is a definition of an API. It describes a list of methods and attributes that a class should have to implement with the desired behavior. This description does not implement any code, but just defines an explicit contract for any class that wishes to implement the interface. Any class can then implement one or several interfaces in whichever way it wants.

While Python prefers duck typing over explicit interface definitions, it may be better to use the latter sometimes. For instance, an explicit interface definition makes it easier for a framework to define functionalities over interfaces.

The benefit is that classes are loosely coupled, which is considered as a good practice. For example, to perform a given process, class A does not depend on class B, but rather on an interface I. Class B implements I, but it could be any other class.

The support for such a technique is built in in many statically typed languages such as Java or Go. The interfaces allow the functions or methods to limit the range of acceptable parameter objects that implement a given interface, no matter what kind of class it comes from. This allows for more flexibility than restricting arguments to given types or their subclasses. It is like an explicit version of duck typing behavior—Java uses interfaces to verify a type safety at compile time, rather than using duck typing to tie things together at runtime.

Python has a completely different typing philosophy than Java, so it does not have native support for interfaces. Anyway, if you would like to have more explicit control of application interfaces, there are generally two solutions to choose from:

Let's take a look at the some of the solutions in the next sections.