Learning is a mess Learning is a mess - 5 months ago 45
Python Question

PyQt QWidget destructor error `AttributeError: 'NoneType' object has no attribute 'path'`

I use a custom widget inheriting from

. This widget may use an online resource: a picture I download from the internet and store in a local file before displaying it in a

When the user closes the window I want the local file to be deleted so I changed the destructor to:

def __del__(self):
if os.path.isfile( self.pictureFilename):
os.remove( self.pictureFilename)

I have:

import os

at the beginning of my script. Strangely, when the main application closes I get the error:

Traceback (most recent call last):

File "/home/XXX/XXX/XXX.py", line 103, in del

AttributeError: 'NoneType' object has no attribute 'path'

It looks like the library gets garbage collected before the destructor gets called. I do not see how to fix that.


Looking at the github code, the problem seems to be that when the widget is closed, the Qt application terminate and sys.exit() is called, so probably the module is garbage collected before__del__ call.


if __name__ == '__main__':
    app = QApplication( sys.argv)
    url = "http://www.transfermarkt.co.uk/cristiano-ronaldo/profil/spieler/8198"
    ex = PlayerWindow( url)
    sys.exit( app.exec_())

To avoid the problem I suggest to use the closeEvent(event) form QWidget http://doc.qt.io/qt-5/qwidget.html#closeEvent

replace yours __del__ function with this:

def closeEvent(self, event):
    if os.path.isfile( self.pictureFilename):
        os.remove( self.pictureFilename)
    del self.profile
    del self.pictureLabel

As a general rule you should try to avoid using __del__ to automatically finalize object with garbage-collection without del object begin called explicitly in your code.