Python Language Variable Scope and Binding The del command


Example

This command has several related yet distinct forms.

del v

If v is a variable, the command del v removes the variable from its scope. For example:

x = 5
print(x) # out: 5
del x
print(x) # NameError: name 'f' is not defined

Note that del is a binding occurence, which means that unless explicitly stated otherwise (using nonlocal or global), del v will make v local to the current scope. If you intend to delete v in an outer scope, use nonlocal v or global v in the same scope of the del v statement.

In all the following, the intention of a command is a default behavior but is not enforced by the language. A class might be written in a way that invalidates this intention.

del v.name

This command triggers a call to v.__delattr__(name).

The intention is to make the attribute name unavailable. For example:

class A:
    pass

a = A()
a.x = 7
print(a.x) # out: 7
del a.x
print(a.x) # error: AttributeError: 'A' object has no attribute 'x'

del v[item]

This command triggers a call to v.__delitem__(item).

The intention is that item will not belong in the mapping implemented by the object v. For example:

x = {'a': 1, 'b': 2}
del x['a']
print(x) #  out: {'b': 2}
print(x['a']) # error: KeyError: 'a'

del v[a:b]

This actually calls v.__delslice__(a, b).

The intention is similar to the one described above, but with slices - ranges of items instead of a single item. For example:

x = [0, 1, 2, 3, 4]
del x[1:3]
print(x) #  out: [0, 3, 4]

See also Garbage Collection#The del command.