why del is not a function or method?
Ned Batchelder
ned at nedbatchelder.com
Mon Oct 16 22:12:57 EDT 2017
On 10/16/17 9:06 PM, bartc wrote:
> On 17/10/2017 01:53, Steve D'Aprano wrote:
>> 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.
>>
>> If we write:
>>
>> x = 123
>> del x
>>
>> 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.
>>
>> `del` is kind of like an "anti-assignment" in that the argument to
>> `del` must
>> be exactly the same sort of expression that can appear on the left
>> hand side
>> of assignment:
>>
>>
>> 123 = 1+1 # illegal
>> del 123 # also illegal
>
> Yet in Stefan Ram's example with del applied to a local 'x', it raised
> an error on:
>
> del x # x not yet assigned to
>
> but an assignment to x would have been fine.
Steve meant that syntactically it had to be valid on the left-hand
side. "x" is a syntactically valid LHS, "1+1" is not.
--Ned.
More information about the Python-list
mailing list