Discover more from Daily Dose of Data Science
A Common Misconception About Deleting Objects in Python
...and here's what "del object" does instead.
Many Python programmers believe that executing
del object always deletes an object.
But that is NOT true.
__del__magic method is used to define the behavior when an object is about to be destroyed by the Python interpreter.
It is invoked automatically right before an object's memory is deallocated.
Thus, by defining this method in your class, you can add a custom functionality when an object is deleted.
As shown in line 5, deleting the object didn't output anything specified in __𝐝𝐞𝐥__.
This means that the object was not deleted.
But it did produce an output the second time (line 7-8).
Why does it happen?
When we execute
Python does not always delete an object
Instead, it deletes the name
varfrom the current scope
Finally, it reduces the number of references to that object by
It is ONLY when the number of references to an object becomes
0 that an object is deleted.
__del__ is executed.
This explains the behavior in the below code.
When we deleted the first reference (
del objectA), the same object was still referenced by
Thus, at that time, the number of references to that object was non-zero.
But when we deleted the second reference (
del objectB), Python lost all references to that object.
As a result, the
__del__ magic method was invoked.
del vardoes not always invoke the
__del__magic method and delete an object.
Instead, here’s what it does:
First, it removes the variable name (
var) from the current scope.
Next, it reduces the number of references to that object by
When the reference count becomes zero, the object is deleted.
👉 Over to you: What are some other common misconceptions in Python?
Thanks for reading Daily Dose of Data Science! Subscribe for free to learn something new and insightful about Python and Data Science every day. Also, get a Free Data Science PDF (350+ pages) with 250+ tips.
👉 Tell the world what makes this newsletter special for you by leaving a review here :)
👉 If you liked this post, don’t forget to leave a like ❤️. It helps more people discover this newsletter on Substack and tells me that you appreciate reading these daily insights. The button is located towards the bottom of this email.
👉 If you love reading this newsletter, feel free to share it with friends!
👉 Sponsor the Daily Dose of Data Science Newsletter. More info here: Sponsorship details.
Find the code for my tips here: GitHub.