Search code examples
pythonmultiple-inheritanceabc

Is it necessary to use abc.ABC for each base class in multiple inheritance?


Consider the following code snippet:

import abc


class Base(abc.ABC):
    @abc.abstractmethod
    def foo(self):
        pass


class WithAbstract(Base, abc.ABC):
    @abc.abstractmethod
    def bar(self):
        pass


class WithoutAbstract(Base):
    @abc.abstractmethod
    def bar(self):
        pass

I have two questions regarding the code above:

  1. Is it necessary to inherit WithAbstract from abc.ABC as well, or is it sufficient to inherit WithoutAbstract only from Base?
  2. What is the pythonic way of going about it? What is the best practice?

Solution

  • There's no technical need to re-inherit ABC, but some linters may complain and people may argue that a class with abstract methods should explicitly inherit ABC to make the intention clear that the class is still abstract, and not a mistake. This especially goes for cases like this, where you don't explicitly declare any obvious abstract methods:

    class C(Base):
        def m(self):
            ...
    

    Did you just miss implementing foo here, or did you intent to keep C an abstract class? Make it explicit by inheriting ABC.