I'm trying to dynamically inherit from a class MyMixin
with metaclasses. Using this excelent answer and this code snippet, I got this working:
class DynamicInheritance(type):
"""
Dinamicaly modify class with some extra mixin.
"""
def __call__(cls, mixin, *args, **kwargs):
new_cls = type(cls.__name__, (mixin, cls), dict(cls.__dict__))
return super(DynamicInheritance, new_cls).__call__(*args, **kwargs)
class MyMixin:
def bye(self):
print("bye")
class Foo(metaclass=DynamicInheritance):
def hello(self):
print("hello")
foo_instance = Foo(MyMixin)
foo_instance.hello()
foo_instance.bye()
Output:
hello
bye
However, when Foo
inherits from an abstract class, things stop working:
from abc import ABC, abstractmethod
class FooAbstract(ABC):
@abstractmethod
def hello(self):
pass
@abstractmethod
def bye(self):
pass
class Foo(FooAbstract, metaclass=DynamicInheritance):
def hello(self):
print("hello")
foo_instance = Foo(MyMixin)
Output:
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
Can someone explain what the problem is?