1

I'm working on simple PyQt5 app which would allow me to edit some files like .xml, .txt

This is how it look right now: enter image description here

Because I need to work with different files I decided to implement superclass which will found and return appropriate subclass depend on file extension.

class WidgetHandler:
    def __new__(cls, path, parent=None):
        ext = os.path.splitext(path)[1].replace('.', '')
        for subclass in cls.__subclasses__():
            if subclass.__name__.lower() == ext:
                return super().__new__(subclass)
        raise NotImplementedError

    def __init__(self, parent, path):
        self._path = path
        self._parent = parent
        self._is_modified = False
        self._create()

    def _create(self):
        raise NotImplementedError

    def _save(self):
        raise NotImplementedError

    def _close(self):
        raise NotImplementedError

    def save(self) -> None:
        if self._is_modified:
            self._save()
            self._is_modified = False

    def close(self) -> None:
        if self._is_modified:
            pass  # TODO Запрос сохранения
        self._close()


class XML(WidgetHandler, QTreeView):
    def _create(self):
        self.setParent(self._parent)
        model = DomModel(self._path)
        # model.dataChanged.connect(lambda: print('Data Changed'))
        self.setModel(model)
        self.expandAll()
        self.setRootIsDecorated(False)
        self.setItemsExpandable(False)
        delegate = XMLDelegate()
        self.setItemDelegate(delegate)

    def _save(self):
        pass

    def _close(self):
        pass

But instead of widget I get this exception: object.__new__(XML) is not safe, use QTreeView.__new__(). Could someone please tell me, what am I doing wrong?

aiscy
  • 113
  • 2
  • 12

1 Answers1

1

The superclass of WidgetHandler is (implicitly) object, since you haven't defined an explicit superclass. So you are calling object.__new__(XML). I Googled your error and found that for Python 2.6,

You can't use object as the terminating class for your inheritance if you want to pass arguments to __new__ or __init__.

I don't know what version of Python you're using, but this could be the source of your problem.

I try to avoid overriding __new__ in general; for this application, you should consider using the factory pattern instead.

Community
  • 1
  • 1
  • 1
    I'm using CPython 3.5.2. The strange thing is that the error only occurs, when one of the classes inherited from QObject. Thank you for point to factory method pattern, it looks like better way than mine :) – aiscy Feb 26 '17 at 12:49