Metaclass conflict when trying to create a Python abstract class that also subclasses a PySide6 class

Viewed 698

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?

0 Answers
Related