Wednesday, May 26, 2010

ABCs - Abstract Base Classes

What's ABCs?
The abc (abstract base class) module was introduced in version 2.6 of Python. The module provides the infrastructure for defining an abstract base class and can typically be used in situations where frameworks need to specify a bunch of interfaces to be implemented to ensure the functionality. An example can be a database application where the framework requires you to provide a Data Access Object with basic CRUD operations and therefore defines an interface, call it UserDao, with the following methods:


  • getById - Return a user entity with the specified id
  • store - store a user entity
  • remove - remove a user entity from the persistent storage
To ensure that developers follows the protocol an abc is introduced.

The UserDao abc
The following example will show you basic usage of the abc module. You should read the module documentation for more details.

Let's create the UserDao abc:
from abc import ABCMeta, abstractmethod

class UserDao:
    This interface should be implemented to provide the framework with
    basic user CRUD operations.
    __metaclass__ = ABCMeta

    def getById(self, userId):
        """ Return the user with the user id. """

    def store(self, user):
        """ Persist the user. """

    def remove(self, user):
        """ Remove the user from the persistent storage. """
If we try to create an instance of this class we get the following error:
>>> dao = UserDao()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: Can't instantiate abstract class UserDao with abstract methods getById, remove, store
In other words, we have a well defined interface to support CRUD operations for User entities and we also have an easy to read documentation of what's expected from a UserDao. If we would rely on duck typing instead of defining the abc, we would need to document the expected behavior for the UserDao elsewhere. I think that the biggest advantage of using ABCs is that you have the interface definition and documentation in one place.

Just to prevent flaming :) I enjoy duck typing and use it a lot but I think that ABCs are useful is some situations.

Implementing the abc
Implementing the UserDao can be done by sub-classing the UserDao.
class User(object):
    def __init__(self): = None = None

class UserDaoImpl(UserDao):

    def getById(self, userId):
        user = User() = userId = 'A User'
        return user

    def store(self, user):
        print "Storing: ",, "-",

    def remove(self, user):
        print "Removing: ",
And to complete the example:
userDao = UserDaoImpl()
user = userDao.getById(10) = "New Name"
Wrap up
I haven't investigated if ABCs introduces any performance overhead but I can't really see why they should. One advantage of using ABCs in frameworks is that you can have the documentation and interface details as a simple Python class. Another advantage is that Python will issue an error if a sub-class doesn't implement all abstract methods/properties of the abc, which is probably the author's intention.


  1. Nice writeup. I'd hacked some of my own abc's in the past, but it's nice to see it included in Python's lib.

  2. Thanks - this was exactly what I needed.