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 :^)