Patternite Logo

Using abstract base classes (ABCs) to define interfaces in Python

0

Interfaces are useful for defining the methods of derived classes that must be implemented. They can be implemented in Python using abstract base classes.

Loading...

We can write more robust code by incorporating interfaces. Interfaces are abstract classes that specify the necessary methods a derived class (AKA child class) must implement, otherwise instantiation will fail. This helps to catch errors sooner, and makes debugging substantially easier. Rather than finding out a class doesn't implement a particular method when that method is called, we can catch this error earlier on, at object instantiation. Additionally, defining an interface makes your code more explicit and readable by clearly specifying what methods are required.

Here we define an interface class called ExampleInterface which uses ABCMeta as its metaclass. This metaclass ensures the interface is defined as an abstract base class (ABC), which can make use of the abstractmethod decorator and can't, itself, be instantiated. We define a method called must_implement_this which is decorated with abstractmethod, indicating this method must be implemented in any derived classes of ExampleInterface.

FailedClass does not implement the must_implement_this method and so instantiating it fails. SuccessfulClass does implement the required method, and so it can be instantiated successfully and used normally.

Real Python has a great blog post which goes over Python interfaces in great detail.

Profile picture for duncster

| edited

Patternite © 2021

Patternite Logo