Are Python class destructors guaranteed to execute before the program ends?

Viewed 395

We can force to execute a destructor with del, and usually just let the garbage collector do its work, but if we define a class destructor in Python, is it guaranteed to execute for every object instantiated?

1 Answers

Short answer: no.

Longer answer: __del__ is not really a destructor in the C++ sense and you probably don't want to use it.

Instead, if you need cleanup, you should probably make the objects into context managers (by writing __enter__ and __exit__ methods) and use them in the with statement, and/or give them close methods which need to be called explicitly. Most classes in Python and widely-used libraries that need to release external resources do both (often by having __enter__ return self and __exit__ call self.close()).

With the garbage collection, there is usually no need to deallocate any memory allocated in __init__ or __new__, as might be done in C++, since it will be collected automatically.

There are uses for the __del__ method, but they're rare.

Related