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.
Some background:
The
__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 del var
:
Python does not always delete an object
Instead, it deletes the name
var
from the current scopeFinally, it reduces the number of references to that object by
1
It is ONLY when the number of references to an object becomes 0
that an object is deleted.
Consequently, __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 objectB
.
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.
So remember…
del var
does 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
1
.When the reference count becomes zero, the object is deleted.
👉 Over to you: What are some other common misconceptions in Python?
👉 Read what others are saying about this post on LinkedIn and Twitter.
👉 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.
I like to explore, experiment and write about data science concepts and tools. You can read my articles on Medium. Also, you can connect with me on LinkedIn and Twitter.