Use cases for del

Duncan Booth duncan.booth at invalid.invalid
Wed Jul 6 10:50:43 EDT 2005


Peter Hansen 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"?
> 
I generally find that unit tests force me to structure the code in a 
cleaner manner, e.g. to not use globals as much, but if you do need to 
delete a global you do it in exactly the same way as you delete anything: 
use the "del" statement:

>>> x = 3
>>> def f():
	global x
	del x

	
>>> x
3
>>> f()
>>> x

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in -toplevel-
    x
NameError: name 'x' is not defined
>>> 

Where I have used 'del' in a unit test it has been to delete local 
variables rather than globals. Specifically I wanted to ensure that some 
data structures were being torn down properly, so the test went something 
like this:

setup: creates a weakref dictionary.

teardown: asserts that the weakref dictionary is empty.

then each test does:

  try:
    create something
    add it to the weakref dictionary
    then test it
  finally:
    use del to remove local variables
    force a garbage collection

Without the del, when a test fails you get two failures, because the 
traceback information keeps the variables alive.



More information about the Python-list mailing list