Use cases for del

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


On Wed, 06 Jul 2005 10:00:02 -0400, Jp Calderone wrote:

> On Wed, 06 Jul 2005 09:45:56 -0400, Peter Hansen <peter at engcorp.com> wrote:
>>Tom Anderson wrote:
>>> How about just getting rid of del? Removal from collections could be
>>> done with a method call, and i'm not convinced that deleting variables
>>> is something we really need to be able to do (most other languages
>>> manage without it).
>>
>>Arguing the case for del: how would I, in doing automated testing,
>>ensure that I've returned everything to a "clean" starting point in all
>>cases if I can't delete variables?  Sometimes a global is the simplest
>>way to do something... how do I delete a global if not with "del"?
>>
> 
> Unless you are actually relying on the global name not being defined, "someGlobal = None" would seem to do just fine.
> 
> Relying on the global name not being defined seems like an edge case.

Er, there is a lot of difference between a name not existing and it being
set to None.

$ cat mymodule1.py

# define some temporary names
a, b, c, d, e, f = 1, 2, 3, 4, 5, 6
# do some work
result = a+b+c+d*e**f
# delete the temp variables
del a
del b
del c
del d
del e
del f

$ cat mymodule2.py

# define some temporary names
a, b, c, d, e, f = 1, 2, 3, 4, 5, 6
# do some work
result = a+b+c+d*e**f
# delete the temp variables
a = None
b = None
c = None
d = None
e = None
f = None

Now import them into Python:

py> import mymodule1, mymodule2
py> dir(mymodule1)
['__file__', '__name__', result]
py> dir(mymodule2)
['__file__', '__name__', result, a, b, c, d, e, f]

Or worse, do this:

py> a = 1
py> from mymodule2 import *
py> a + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

It is bad enough that from module import * can over-write your variables
with the modules' variables, but for it to do so with DELETED variables is
unforgivable.



-- 
Steven.




More information about the Python-list mailing list