why del is not a function or method?

Chris Angelico rosuav at gmail.com
Mon Oct 16 12:31:08 EDT 2017


On Tue, Oct 17, 2017 at 3:18 AM, Stefan Ram <ram at zedat.fu-berlin.de> wrote:
> bartc <bc at freeuk.com> writes:
>>What about del team[2]?
>
>   All arguments of a call are evaluated before the callable
>   called then is incarnated with the values obtained. Assume,
>   »team[ 2 ]« is bound to »8«. Then, the call
>
> f( team[ 2 ])«
>
>   is equivalent to
>
> f( 8 )
>
>   , and so »f« doesn't stand a chance of deleting »team[ 2 ]«.
>
>   The evaluation rules for calls do not apply to the del-
>   statement, however. Therefore,
>
> del team[ 2 ]
>
>   is /not/ equivalent to
>
> del 8
>
>   , and »del« can delete »team[ 2 ]« just fine. (Because the
>   implementation can use whatever means available to it,
>   since it is not bound to follow the evaluation rules for
>   callables.)

Right, but you *could* implement a function that takes the two parts
and does the assignment or deletion:

def f(lst, idx):
    del lst[idx]

f(team, 2)

The reason that 'del' absolutely has to be a statement is that it can
work on simple names, too:

del team

There's no way to do THAT part with a function call (it's basically
the opposite of assignment), so 'del' has to be a statement. Since
it's a statement, it may as well be able to do more than just simple
names, which means we have a consistent way to delete items from
arbitrary objects:

del globals()["foo"] # dicts
del sys.argv[1] # lists
etc

(Although you can't do this with sets. Sets are manipulated
exclusively through methods and operators.)

ChrisA



More information about the Python-list mailing list