When (and why) to use del?
Philip Semanchuk
philip at semanchuk.com
Wed Dec 10 17:25:13 EST 2008
On Dec 10, 2008, at 5:23 PM, Gabriel Genellina wrote:
> 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.
Thanks for the clarification -- I didn't know that.
More information about the Python-list
mailing list