When (and why) to use del?
rdmurray at bitdance.com
rdmurray at bitdance.com
Tue Dec 9 15:27:42 EST 2008
On Tue, 9 Dec 2008 at 18:55, Duncan Booth wrote:
> Albert Hopkins <marduk at letterboxes.org> wrote:
>
>> 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?
>>
> It is probably a complete waste of time, but there are situations where
> code similar to this can be useful:
>
> def otherfunction():
> try:
> # some stuff
> except SomeException, e:
> # more stuff
> del e
> raise
> return
>
> The point of code like this is that when a function exits by throwing an
> exception the traceback includes a reference to the stack frame and all the
> local variables. In some situations that can result in large data
> structures not being freed for a very long time (e.g. until another
> exception is thrown that is handled at the same level). So, *in very
> specialised situations* it may be important to delete particular names from
> the local namespace.
If I'm reading http://www.python.org/dev/peps/pep-3110/ right, Python
3.0 eliminates even this use case :)
I have had occasions to use del, when I don't want the variable in the
namespace anymore for some reason (for example, when I'm later going to
be scanning the namespace for some reason).
--RDM
More information about the Python-list
mailing list