By Chum Mapa
When I initially started looking into the ABC (abstract base class) module, it was hard for me to understand the need for it. Learning how to use ABCs was fairly easy, and the documentation was straightforward, which is what sucked me into learning more. The rationale behind when to use ABC and why it’s useful was the difficult part for me to wrap my mind around. That said, once I was able to conceptualize the use cases, it became more clear as to why ABCs are helpful.
If you’re new to ABCs, I hope you find this post comprehensive. Some understanding of OOP and inheritance is needed.
Quick Beginner Note on Class Behavior:
One of the main focuses of object oriented programming (OOP) is the behavior of a class. We consider behavior of classes more than the structure. I am less interested in knowing if something is a list or a numpy array, for example, and very interested in if it behaves like those types — How is it indexed, can you append elements, etc.
Both of the above inherit from a parent class payroll
. For our purposes, it doesn’t necessarily matter what the parent class is, we mostly just care that it runs the status
method.
Unlike standard (or “concrete”) classes, an ABC requires its classes to define their behavior a certain way when they are instantiated.
What is an ABC?
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes cannot be instantiated, and require subclasses to provide implementations for the abstract methods.
An ABC or Abstract Base Class is a class that cannot be implemented on its own. It’s a type of metaclass that contains one or more abstract methods that need to be completed .
By using an abstract class we can define a generalized structure of the methods without providing complete implementations of every method. Abstract methods that are defined in the abstract class generally don’t have the body, but it is possible to have abstract methods with implementations in the abstract class and if any subclass is getting derived from such abstract class needs to provide the implementation for such methods. If any abstract method is not implemented by the derived class then it will throw an error. The abstract class object can’t be directly created, but when we use this abstract class to provide certain functionalities to a base class or child class it can do that by creating the object of the base class.
from abc import ABC, abstractmethod
The abstract class, item, inherits from the ABC module which you can import at the beginning of your Python file using the command from abc import ABC, abstractMethod
. The ABC class is an abstract method that does nothing and will return an exception if called.
Abstract Decorators
When we’ve imported the abc library, we must decide which methods are abstract methods, and mark them with the @abstractmethod
decorator.
A decorator is a prefix that tells us how the function or class is to be called and used. We use basic decorators all the time when we create properties for a class using the @property
decorator.
The property decorator tells us that this function method is a property, which means we can access it as though it were an attribute. The @abstractmethod
decorator does just the opposite: it tells us we cannot access a method until it has been overridden by a subclass.
The child class must override all the methods in the abstract class using a line of code in the __init__ function: super().__init__(name)
. For each method bearing the @abstractmethod
decorator, there must be a corresponding method with the same name in the child classes. If we were to make a class for short stories, and it did not have one of these methods, then it would not work.
Demo:
from abc import ABC, abstractmethodclass MontyPython(ABC):
@abstractmethod
def joke(self):
pass
@abstractmethod
def punchline(self):
pass
@property
def response(self):
pass
Creating a subclass
class First(MontyPython):
def joke(self):
return "Please! This is supposed to be a happy occasion." def punchline(self):
return "Let's not bicker and argue over who killed who." response = "Hahahaha"
Testing the subclass:
c = First()c.joke()'Please! This is supposed to be a happy occasion.'c.punchline()'Let's not bicker and argue over who killed who.'c.response'Hahahaha'
Checking the ABC inheritance:
print(issubclass(First,MontyPython))
print(isinstance(First(), MontyPython))True
True
ABCs and Data Science
Experienced Python developers may have workarounds for some of these use cases, but I believe ABCs can be a valuable tool for my data science projects in the following ways:
- Large project organization: with the ease and flexibility of instantiating concrete classes, it’s not hard to imagine scenarios where a growing number of class objects make it — 1. Unmanageable: making minor changes has the potential to unknowingly break your code wherever that class is being used. 2. Unorganized: with ABC’s organized in terms of promised behavior, and non-specific.
There are many powerful dispatch philosophies that are in direct contrast to the classic OOP requirement of behavior being strictly encapsulated within an object, examples being rule or pattern-match driven logic. — Python Developer’s Guide
- Avoid missing values during scraping: For example, we could create an abstract class named Item to reuse throughout a Python program to scrape news articles online. The program could contain child classes for both articles and videos that inherit from the Item class. Adding methods to require specific data before appending to a particular database would be useful.