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 any reason to keep del
in python, or is it a vestige of Python's pre-garbage collection days?
Deleting a variable is different than setting it to None
Deleting variable names with
del
is probably something used rarely, but it is something that could not trivially be achieved without a keyword. If you can create a variable name by writinga=1
, it is nice that you can theoretically undo this by deleting a.It can make debugging easier in some cases as trying to access a deleted variable will raise an NameError.
You can delete class instance attributes
Python lets you write something like:
If you choose to dynamically add attributes to a class instance, you certainly want to be able to undo it by writing
Just another thinking.
When debugging http applications in framework like Django, the call stack full of useless and messed up variables previously used, especially when it's a very long list, could be very painful for developers. so, at this point, namespace controlling could be useful.
Once I had to use:
because using only:
didn't release the serial port fast enough to immediately open it again. From that lesson I learned that
del
really meant: "GC this NOW! and wait until it's done" and that is really useful in a lot of situations. Of course, you may have asystem.gc.del_this_and_wait_balbalbalba(obj)
.There's this part of what
del
does (from the Python Language Reference):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.)
Yet another niche usage: In pyroot with ROOT5 or ROOT6, "del" may be useful to remove a python object that referred to a no-longer existing C++ object. This allows the dynamic lookup of pyroot to find an identically-named C++ object and bind it to the python name. So you can have a scenario such as:
Hopefully, this niche will be closed with ROOT7's saner object management.
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 inos.walk
and wish to delete an element in the directory. I would not consider a keyword useful for this though, since one could just make a[].remove(index)
method (the.remove
method is actually search-and-remove-first-instance-of-value).