Deleting variables [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

Steven D'Aprano steve at REMOVETHIScyber.com.au
Wed Jul 6 11:15:16 EDT 2005


On Wed, 06 Jul 2005 14:28:55 +0100, Tom Anderson wrote:

>> del -> delete
> 
> How about just getting rid of del? Removal from collections could be done 
> with a method call, 

Which would be called object.del() I presume. And that opens a big
can of worms.

Suppose we have a list L = [4, 3, 2, 1, 0], what should L.del(1) do?

It looks like it should result in L becoming [4, 3, 2, 0]. An easy mistake
to make, if you forget that the argument is (presumably) an index.
You could make it clear by insisting on L.del[1] but that requires a big
change in Python's syntax.

What should L.del() do, with no arguments? Raise an error? 

Now, you have something like this:

class thing:
    pass
obj = thing()
obj.alpha = [4, 3, 2, 1, 0]
obj.beta = 5

Python's object model suggests that obj.alpha.del() should call
alpha's del method, in the same way that obj.alpha.append() would call
alpha's append method.

So how do you delete obj.alpha? obj.del("alpha") might work. But what if
obj itself is a mapping, with a key "alpha" as well as an attribute alpha.
Which one should obj.del("alpha") delete?

Now, if you said that L.del() should raise an exception earlier, what
about obj.beta.del()?


Presumably every object automatically has a del method, so you
don't have to program a del method yourself. obj.del is a method object.
So it has a del method. (Yes, sometimes you want to delete methods.
Functions are first class objects in Python.) Which has a del method.
Which has a del method. 

What should obj.del.del.del.del.del.del.del.del.del() do?


> and i'm not convinced that deleting variables is 
> something we really need to be able to do (most other languages manage 
> without it).

Most other languages don't have namespaces that can get polluted, or
on-the-fly creation of variables. Most other languages don't consider
variables to be simply attributes of a module object. And most other
languages don't allow you to run interactive sessions where it is easy to
mistakenly make variables you don't want.

py> x = 1
py> u = x+2  # oops, typo, meant y not u
py> del u  # prevent confusion in the programmer's mind

It is also useful sometimes to delete a module object from the top level
namespace before re-importing it, rather than merely reloading it. That
requires being able to delete a variable.

In summary: del being a keyword works. del() being an object method is
unclear, confusing and complicated.


-- 
Steven.





More information about the Python-list mailing list