why del is not a function or method?

bartc bc at freeuk.com
Mon Oct 16 13:21:01 EDT 2017


On 16/10/2017 17:55, Oren Ben-Kiki wrote:
> True... technically, "Deletion of a name removes the binding of that name
> from the local or global namespace". Using `x.del()` can't do that.
> 
> That said, I would hazard to guess that `del x` is pretty rare (I have
> never felt the need for it myself). Ruby doesn't even have an equivalent
> operation, and doesn't seem to suffer as a result.

It just seems the peculiar way that Python works:

    pass      # 1
    pass      # 2
    x = 10    # 3
    del x     # 4
    pass      # 4

In the above code, x doesn't actually exist in the namespace until line 
3. Trying to use x on lines 1 or 2 would cause an 'undefined' error.

del x effectively removes it from the namespace so trying to use it on 
line 4 generates the same 'undefined' error.

However, the byte-code still needs to be aware of x: at the time when 
line 1 is executed, the byte-code for line 3 already exists and it will 
need to contain a reference to x.

This could have been done in other ways by simply having 'x' always in 
the namespace, but not bound to anything ('undefined). But then the 
equivalent of del x would still have needed something special, for example:

    x = anything    # any other undefined name

which is currently not allowed.

-- 
bartc



More information about the Python-list mailing list