This is not what del does. It is __del__ that __del__ has the same name as del , because they are not related to each other. In modern terminology, the __del__ method will be called a finalizer, not a destructor, and the difference is important.
The small difference is that it is easy to guarantee when the call to the destructor is called, but you have very few guarantees as to when __del__ will be called, and it will never be called. This can lead to various circumstances.
If you want lexical coverage, use the with statement. Otherwise, call myobj.close() directly. The del operator only removes links, not objects.
I found another answer ( link ) to another question that answers this in more detail. Unfortunately, the accepted answer to this question contains flagrant errors.
Edit: As commenters noted, you need to inherit from object . That's fine, but it's still possible that __del__ will never be called (you might be lucky). See related answer above.
source share