Search code examples
pythonpython-3.xabstract-classabc

What is the difference between abstractclass(metaclass=ABCMeta) and class abstractclass(ABC) in Python ABC module?


I have seen two ways for defining Abstract Classes in Python.

This one:

from abc import ABCMeta, abstractmethod
class AbstactClass(metaclass = ABCMeta):

And this one:

from abc import ABC, abstractmethod
class AbstractClass2(ABC):

What are there differences between them and what are the respective usage scenarios?


Solution

  • There is no actual functional difference. The ABC class is simply a convenience class to help make the code look less confusing to those who don't know the idea of a metaclass well, as the documentation states:

    A helper class that has ABCMeta as its metaclass. With this class, an abstract base class can be created by simply deriving from ABC avoiding sometimes confusing metaclass usage

    which is even clearer if you look at the the implementation of abc.py, which is nothing more than an empty class that specifies ABCMeta as its metaclass, just so that its descendants can inherit the type:

    class ABC(metaclass=ABCMeta):
        """Helper class that provides a standard way to create an ABC using
        inheritance.
        """
        __slots__ = ()