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
To add a few points to above answers:
del x
Definition of x
indicates r -> o
(a reference r
pointing to an object o
) but del x
changes r
rather than o
. It is an operation on the reference (pointer) to object rather than the object associated with x
. Distinguishing between r
and o
is key here.
locals()
.globals()
if x
belongs there.x
belongs to, not where x
points to. The only physical change in memory is this. For example if x
is in a dictionary or list, it (as a reference) is removed from there(and not necessarily from the object pool). In this example, the dictionary it belongs is the stack frame (locals()
), which overlaps with globals()
.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. 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).
One place I've found del
useful is cleaning up extraneous variables in for loops:
for x in some_list:
do(x)
del x
Now you can be sure that x will be undefined if you use it outside the for loop.
Force closing a file after using numpy.load:
A niche usage perhaps but I found it useful when using numpy.load to read a file. Every once in a while I would update the file and need to copy a file with the same name to the directory.
I used del
to release the file and allow me to copy in the new file.
Note I want to avoid the with
context manager as I was playing around with plots on the command line and didn't want to be pressing tab a lot!
See this question.
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.)
I would like to elaborate on the accepted answer to highlight the nuance between setting a variable to None
versus removing it with del
:
Given the variable foo = 'bar'
, and the following function definition:
def test_var(var):
if var:
print('variable tested true')
else:
print('variable tested false')
Once initially declared, test_var(foo)
yields variable tested true
as expected.
Now try:
foo = None
test_var(foo)
which yields variable tested false
.
Contrast this behavior with:
del foo
test_var(foo)
which now raises NameError: name 'foo' is not defined
.