Jason Baker Jason Baker - 10 months ago 50
Python Question

When is del useful in python?

I can't really think of any reason why python needs the

keyword (and most languages seem to not have a similar keyword). For instance, rather than deleting a variable, one could just assign
to it. And when deleting from a dictionary, a
method could be added.

Is there any reason to keep
in python, or is it a vestige of Python's pre-garbage collection days?

Answer Source

Firstly, you can del other things besides local variables

del list_item[4]
del dictionary["alpha"]

Both of which should be clearly useful. Secondly, using del on a local variable makes the intent clearer. Compare:

   del foo


   foo = None

I know in the case of del foo that the intent is to remove the variable from scope. It's not clear that foo = None is doing that. If somebody just assigned foo = None I might think it was dead code. But I instantly know what somebody who codes del foo was trying to do.