- Daily Dose of Data Science
- Posts
- A Common Misconception About Deleting Objects in Python
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 scope
Finally, 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?
๐ 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.
Reply