Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Destructor usage in python __del__()

Will the following not cause issue of freeing memory twice? Why is python3 destroying an object
when it has already been destroyed by the programmer?

class Example:

    # Initializing
    def __init__(self):
        print('object created.')

    # Deleting (Calling destructor)
    def __del__(self):
        print('Destructor called, object deleted.')


obj = Example()
obj.__del__()

Output:

object created.
Destructor called, object deleted.
Destructor called, object deleted.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

By calling __del__() you’re just calling a method on the instance, without any special meaning.

The __del__() method, both yours and by default does absolutely nothing. Moreover, it is not a destructor but rather a finalizer:

Called when the instance is about to be destroyed. This is also called
a finalizer or (improperly) a destructor.

Python’s memory allocation is completely internal. The only weak guarantee in Python is that if a method __del__() exists, it will be called right before the object is deleted from memory. It may even be called twice or thrice on certain occasions if the object get resurrected, or not at all in case of daemon threads.

For more info, please read the documentation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading