When (and why) to use del?

pruebauno at latinmail.com pruebauno at latinmail.com
Tue Dec 9 18:02:42 CET 2008

On Dec 9, 11:35 am, Albert Hopkins <mar... at letterboxes.org> wrote:
> I'm looking at a person's code and I see a lot of stuff like this:
>         def myfunction():
>             # do some stuff stuff
>             my_string = function_that_returns_string()
>             # do some stuff with my_string
>             del my_string
>             # do some other stuff
>             return
> and also
>         def otherfunction():
>             try:
>                 # some stuff
>             except SomeException, e:
>                 # more stuff
>                 del e
>             return
> I think this looks ugly, but also does it not hurt performance by
> preempting the gc?  My feeling is that this is a misuse of 'del'. Am I
> wrong?  Is there any advantage of doing the above?

If this is CPython (the standard Python) the extra del(s) in the
examples you gave are just garbage and good for nothing. The reason
being that they are inside a function; as soon as the program exits
the function the variable gets deleted automatically. The only reason
to use del would be a global variable in long running program that
uses a lot of space, but global variables should be avoided for other
reasons anyway. I never ever used del in my programs only on the
interactive interpreter prompt after doing foolish things like x=open

More information about the Python-list mailing list