PyQt6 annoyance 'object has no attribute'

Published: 14-11-2024


While merging a medium size patch and updating code according on some project, there was a exception raised 'object has no attribute', looking at the code it is clear that the requested attribute is present. So WTF is going on? I haven't dived into the PyQt6 or maybe even Qt source yet, but what is happening is that a wrong exception is raised that confuses developers.

The example code below yields the following error:

`AttributeError: 'TestClass' object has no attribute 'does_not_exist'`

The error that any coder would have expected (how it should be):

`AttributeError: 'MyClass' object has no attribute '_does_not_exist'`

Example code:

from PyQt6.QtCore import QObject

class MyClass:
    def __init__(self):
        self._data = {}

    @property
    def data(self):
        return self._data

    @property
    def does_not_exist(self):
        return self._does_not_exist

class TestClass(QObject):
    def __init__(self, parent=None):
        QObject.__init__(self, parent)
        self.myclass = MyClass()

    @property
    def data(self):
        return self.myclass.data

    @property
    def does_not_exist(self):
        return self.myclass.does_not_exist

t = TestClass()
print(t.data)
print(t.does_not_exist)