Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is del useful in Python?

I can't really think of any reason why Python needs the del keyword (and most languages seem to not have a similar keyword). For instance, rather than deleting a variable, one could just assign None to it. And when deleting from a dictionary, a del method could be added.

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

like image 912
Jason Baker Avatar asked May 27 '11 01:05

Jason Baker


People also ask

When should I use Del?

The preposition de is translated as "of," "from," or "about," but de also can mean "by," "in," or other prepositions in some cases. Del is simply the contraction of de and the definite article el (not él), so we use del in place of de el.

Do I need to use del in Python?

When is del useful in python? You can use it to remove a single element of an array instead of the slice syntax x[i:i+1]=[] . This may be useful if for example you are in os. walk and wish to delete an element in the directory.

What does Del Do in dictionary Python?

The Python del statement deletes an object. Because key-value pairs in dictionaries are objects, you can delete them using the “del” keyword. The “del” keyword is used to delete a key that does exist. It raises a KeyError if a key is not present in a dictionary.

What is __ del __ in Python?

The __del__() method is a known as a destructor method in Python. It is called when all references to the object have been deleted i.e when an object is garbage collected.


2 Answers

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 

to

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.

like image 167
Winston Ewert Avatar answered Oct 18 '22 03:10

Winston Ewert


There's this part of what del does (from the Python Language Reference):

Deletion of a name removes the binding of that name from the local or global namespace

Assigning None to a name does not remove the binding of the name from the namespace.

(I suppose there could be some debate about whether removing a name binding is actually useful, but that's another question.)

like image 31
Greg Hewgill Avatar answered Oct 18 '22 03:10

Greg Hewgill