When (and why) to use del?

malkarouri malkarouri at gmail.com
Tue Dec 9 11:59:40 EST 2008


On 9 Dec, 16:35, 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?

As far as I understand it, this does not do anything. Let me explain.
The del statement doesn't actually free memory. It just removes the
binding from the corresponding namespace. So in your first example,
my_string cannot be used after the deletion. Of course, if the string
referenced by my_string was referenced by some other name then it will
still stay in memory.

In both your examples, the bindings are going to be removed anyway
immediately after the del statement, when returning from the function.
So, the del is redundant. If for some reason, however, you are not
breaking your work into functions (not advisable) you will have a huge
list of commands with no deletion and start to use huge amounts of
memory. Solution: divide your work into functions.

It is sometimes, however, useful to preempt the gc. This can be done
when you know that this is a good time to do chores, e.g. on an
application's idle period. Calling gc.collect() is useful here.

Regards,

Muhammad Alkarouri



More information about the Python-list mailing list