1

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?
Woltan
  • 13,723
  • 15
  • 78
  • 104

2 Answers2

1

WithAbstract inherits from Base which already inherits from abc.ABC so you don't have to inherit from abc.ABC again.

Unless all of a sudden Base ceases to inherit from abc.ABC and your code breaks.

I don't know about pythonic but I would tend to avoid multiple inheritance. True, it's not as problematic as in other languages like C++ but simple is better than complex.

If all the descendants of Base have to use @abc.abstractmethod decorator, then it's better to make it available from Base to avoid unnecessary copy/paste when creating a new child class.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

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.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Both answers from deceze and Jean-François Fabre pretty much sum up how to deal with `ABC` base classes. I voted this answer to be the "correct" answer, because it also includes some best practice thought concerning the explicit marking of an abstract class. – Woltan Jan 16 '23 at 09:03