When (and why) to use del?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Dec 10 17:23:09 EST 2008


En Tue, 09 Dec 2008 15:29:17 -0200, Philip Semanchuk  
<philip at semanchuk.com> escribió:
> On Dec 9, 2008, at 11:35 AM, Albert Hopkins wrote:
>
>>        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
>>
>> 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.

Note that CPython has a garbage collector AND uses reference counts.  
Objects are deallocated *immediately* as soon as their reference count  
reaches zero. The GC is used only to detect and dispose of reference  
cycles.
So, if you `del` a name and it happens to be the last reference to certain  
object, the object is immediately destroyed; the GC isn't involved at all.

> 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.

Yes, I've seldom used "del" in those circumstances too. And inside an  
exception handler. I can't remember of other cases.

-- 
Gabriel Genellina




More information about the Python-list mailing list