When (and why) to use del?
Philip Semanchuk
philip at semanchuk.com
Tue Dec 9 12:29:17 EST 2008
On Dec 9, 2008, at 11:35 AM, Albert Hopkins 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?
The code above doesn't pre-empt the GC, it just provides it with a
useful hint. When you del a variable you just tell the GC, "I'm done
with this, so you might be able to get rid of it next time you collect
garbage". If the variable wasn't explicitly del-ed, you'd still hold a
reference and the GC would be unable to collect it while the section
"do some other stuff" runs.
HOWEVER, I don't code that way and I've never seen anyone else do
that. It's ugly, as you said, and represents a lot of mental clutter
for anyone reading/writing the code. And since the GC might not even
run during the "do some other stuff" section, there might be no
advantage at all to the explicit del.
On rare occasions (I can think of once or twice in all the Python I've
written) I'll del a variable that might use lots of memory if it
wouldn't otherwise get dereferenced quickly (say, by going out of
scope). But in my experience that's quite rare.
Cheers
Philip
More information about the Python-list
mailing list