Tuesday, April 12, 2016

The Shocking Truth About The Del Statement


The del statement doesn’t actually delete objects


Wait … what?

question-mark-1020165_1280.jpg

To understand this, you need to know a little bit about how Python handles variables and assignment.


Objects, references, and the = operator


An assignment statement looks like this:
<variable-name> = <object>
The assignment statement has 3 parts
  1. The variable name.
  2. The object being assigned to the variable.
  3. The = operator, which creates a reference from the variable name to the object.
Point #3 is key to understanding how all this works. It might help if you imagine drawing an arrowhead on the = sign, like this
<variable-name> ⇒ <object>
This emphasizes the fact that variables don’t contain objects, they refer to objects.

If I assign the same object to two variables, they each contain a reference to that object.


Then if I delete the "X" variable here’s what happens

Clearly, the int(29) object didn’t get deleted. You know that because you can still refer to it through the "Y" variable. It was the reference from X to 29 that got deleted. And because you can’t have a variable that doesn’t refer to anything, the variable “X” also got deleted.

So how do you delete an object?


Well, you really can’t. Python does something called “reference counting”. It keeps track of how many references exist to an object. When the number of references drops to zero, the object is marked for “garbage collection”. Exactly how and when garbage collection happens is outside your control.

References