why del is not a function or method?

Ben Finney ben+python at benfinney.id.au
Mon Oct 16 23:40:14 EDT 2017


Steve D'Aprano <steve+python at pearwood.info> writes:

> On Tue, 17 Oct 2017 03:16 am, Oren Ben-Kiki wrote:
>
> > That doesn't explain why `del` isn't a method though.
>
> `del` cannot be a method or a function, because the argument to `del`
> is the name of the variable, not the contents of the variable.

Since a Python “variable” does not have contents, this is IMO another
instance where using the term “variable” is not helpful.

    >>> x = 123
    >>> y = [0, x, 2, x, 4]

Neither of the names ‘x’ nor ‘y’ have content; they are references to
objects. The list itself also has references, which the Python code can
use to get at the items.

    >>> y
    [0, 123, 2, 123, 4]
    >>> y[1]
    123

So when we give an argument to ‘del’, that argument is not always a
“variable”; it is always a reference.

We can delete one item from a list, because that item is accessed via a
reference; we give the same reference as argument to ‘del’::

    >>> del y[1]

Both ‘x’ and ‘y’ remain bound. The reference that was at index 1 of the
above list is deleted.

    >>> x
    123
    >>> y
    [0, 2, 123, 4]

> then `del` needs to delete the *name* "x", not the value of x, namely
> 123. If del were a function or method, it would only see the value,
> 123, and have no idea what the name is.

Hopefully when one thinks in terms of references – and the use of a
non-name reference, above, may make that distinction clear – the
operation of ‘del’ is easier to understand.

-- 
 \                  “The shortest distance between two points is under |
  `\                                      construction.” —Noelie Alito |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list