1

I'm playing around with Abstract Base Classes and noticed some funky behaviour which I couldn't understand.

Here is an example of behaviour that I would expect - a subclass inheriting from an ABC with an abstract method, but without implementing said abstract method:

from abc import ABC, abstractmethod

class MyABC(ABC):

    @abstractmethod
    def foo(self):
        pass

class MySubClass(MyABC):
    pass

x = MySubClass()  # Raises error for MySubClass not implementing 'foo'

However, here is an example resulting in something I don't understand - even though I don't implement the abstract method in the subclass, it doesn't throw an error like in the previous example. The only thing that's changed is that I'm inheriting a namedtuple as well:

from abc import ABC, abstractmethod
from collections import namedtuple

my_tuple = namedtuple("_some_class", ["arg"])

class MyABC(ABC):

    @abstractmethod
    def foo(self):
        pass

class MySubClass(MyABC, my_tuple):
    pass

x = MySubClass("..")  # Doesn't raise an error, even though 'foo' isn't implemented!

I also came across some answers (1, 2, 3) that talked about multiple inheritance with named tuples or with ABCMeta classes/mixins, but I couldn't quite piece it together for my particular use-case. I tried a couple of things, but always ended up with errors such as Multiple inheritance with NamedTuple is not supported and multiple bases have instance lay-out conflict.

TLDR; The aim of this is to get MySubClass to throw an error about foo() not being implemented, whilst inheriting from an ABC and a collections.namedtuple.

Any help for understanding this behaviour would be great :^)

Diggy.
  • 6,744
  • 3
  • 19
  • 38
  • Also, fwiw, `x.foo()` calls the abstract method. – Mark Jan 14 '22 at 15:52
  • 1
    The [answer here](https://stackoverflow.com/questions/37398966/python-abstractmethod-with-another-baseclass-breaks-abstract-functionality) may be helpful. Seems like it is not specific to `namedtuple`. – Mark Jan 14 '22 at 15:58
  • Great, thanks @Mark - that helped a bunch! Take care :^) – Diggy. Jan 14 '22 at 16:03

0 Answers0