I'm trying to create an abstract base class that also inherits an arbitrary PySide6 class. However, the following produces the error TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
.
from abc import ABC, abstractmethod
from PySide6.QtWidgets import QApplication, QWidget
class MyBaseWidget(QWidget, ABC):
def __init__(self, parent=None):
super().__init__(parent=parent)
@abstractmethod
def foo(self):
pass
class MyConcreteWidget(MyBaseWidget):
def __init__(self, parent=None):
super().__init__(parent=parent)
app = QApplication([])
widget = MyConcreteWidget()
widget.show()
app.exec_()
I tried to resolve this using the solution seen below (inspiration came from Resolving metaclass conflicts, http://www.phyast.pitt.edu/~micheles/python/metatype.html, Multiple inheritance metaclass conflict, etc.).
class MyMeta(ABCMeta, type(QWidget)): pass
class MyBaseWidget(QWidget, metaclass=MyMeta):
def __init__(self, parent=None):
super().__init__(parent=parent)
@abstractmethod
def foo(self):
pass
class MyConcreteWidget(MyBaseWidget):
def __init__(self, parent=None):
super().__init__(parent=parent)
app = QApplication([])
widget = MyConcreteWidget()
widget.show()
app.exec_()
This executes without error, but I was expecting an error like TypeError: Can't instantiate abstract class MyConcreteWidget with abstract methods foo
when instantiating MyConcreteWidget
. Not being able to enforce the base class's interface really takes away the benefit of having an abstract base class. Any solutions?
QWidget
class (QWidget
is arbitrary...it could be any Qt class) so that others that inherit it are required to implement the abstract method(s). The problem doesn't necessarily require the use of metaclasses, butABCMeta
is conflicting withQWidget
's metaclass so my original thought was that I needed to solve that metaclass conflict. – Ceresinfoo
in their own way, which is why it's abstract inMyBaseWidget
; there is no default implementation offoo
. The metaclass conflict is a side effect of what I'm trying to achieve since PythonABC
class don't play well with Qt classes. – Ceresin