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 deletin
del
is often seen in __init__.py
files. Any global variable that is defined in an __init__.py
file is automatically "exported" (it will be included in a from module import *
). One way to avoid this is to define __all__
, but this can get messy and not everyone uses it.
For example, if you had code in __init__.py
like
import sys
if sys.version_info < (3,):
print("Python 2 not supported")
Then your module would export the sys
name. You should instead write
import sys
if sys.version_info < (3,):
print("Python 2 not supported")
del sys
Once I had to use:
del serial
serial = None
because using only:
serial = None
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 a system.gc.del_this_and_wait_balbalbalba(obj)
.
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.
The "del" command is very useful for controlling data in an array, for example:
elements = ["A", "B", "C", "D"]
# Remove first element.
del elements[:1]
print(elements)
Output:
['B', 'C', 'D']
Using "del" explicitly is also better practice than assigning a variable to None. If you attempt to del a variable that doesn't exist, you'll get a runtime error but if you attempt to set a variable that doesn't exist to None, Python will silently set a new variable to None, leaving the variable you wanted deleted where it was. So del will help you catch your mistakes earlier
I think one of the reasons that del has its own syntax is that replacing it with a function might be hard in certain cases given it operates on the binding or variable and not the value it references. Thus if a function version of del were to be created a context would need to be passed in. del foo would need to become globals().remove('foo') or locals().remove('foo') which gets messy and less readable. Still I say getting rid of del would be good given its seemingly rare use. But removing language features/flaws can be painful. Maybe python 4 will remove it :)