English

FAQ: Why is the del statement in Python unable to delete data referenced by variables?

Question

Why is the del statement in Python unable to delete data referenced by variables?

Answer

The intent of the del function, known as the 'delete' function, in regards to the deletion of a variable name, is to remove the bindings of the name from the local or global namespace. This pure Python function is not intended to physically delete the data on disk or in memory that is referenced by the variable.

For example, code is written that executes the following tasks.

1. Use a variable to point to an input table
2. Use a variable to point to an output table
3. Check if the output table exists, and if so, delete it from existence
4. Copy the input table to the location of the output table

In the above requirements, the del statement cannot be used to delete the data on disk - it is not like the 'Delete' key on a keyboard to delete a file. If the code is run in this manner, as shown in the following image, a NameError is thrown when referencing the variable unbound via the call to the del statement.
[O-Image]
To delete the data on disk, use the appropriate function designed to delete files from disk or memory. In this case, use one of the functions provided by Esri's ArcPy module.
[O-Image]
In scenarios where the data being deleted is analyzable by the system, pure Python methods can be used to delete the data.
[O-Image]
In summary, the del statement in Python is not designed to physically remove data from disk. As per the Python documentation, 'Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. If the name is unbound, a NameError exception will be raised.'

Official Python Documentation: Section 6.5 - The del statement

Related Information