[ACCEPTED]-Using explicit del in python on local variables-coding-style

Accepted answer
Score: 38

I don't remember when I last used del -- the 27 need for it is rare indeed, and typically 26 limited to such tasks as cleaning up a module's 25 namespace after a needed import or the like.

In 24 particular, it's not true, as another (now-deleted) answer 23 claimed, that

Using del is the only way to make 22 sure a object's __del__ method is called

and it's 21 very important to understand this. To help, let's 20 make a class with a __del__ and check when it is 19 called:

>>> class visdel(object):
...   def __del__(self): print 'del', id(self)
... 
>>> d = visdel()
>>> a = list()
>>> a.append(d)
>>> del d
>>>

See? del doesn't "make sure" that __del__ gets 18 called: del removes one reference, and only 17 the removal of the last reference causes __del__ to 16 be called. So, also:

>>> a.append(visdel())
>>> a[:]=[1, 2, 3]
del 550864
del 551184

when the last reference 15 does go away (including in ways that don't 14 involve del, such as a slice assignment as 13 in this case, or other rebindings of names 12 and other slots), then __del__ gets called -- whether 11 del was ever involved in reducing the object's 10 references, or not, makes absolutely no difference 9 whatsoever.

So, unless you specifically need 8 to clean up a namespace (typically a module's 7 namespace, but conceivably that of a class 6 or instance) for some specific reason, don't 5 bother with del (it can be occasionally handy 4 for removing an item from a container, but 3 I've found that I'm often using the container's 2 pop method or item or slice assignment even 1 for that!-).

Score: 4

No.

I'm sure someone will come up with some 5 silly reason to do this, e.g. to make sure 4 someone doesn't accidentally use the variable 3 after it's no longer valid. But probably 2 whoever wrote this code was just confused. You 1 can remove them.

Score: 3

When you are running programs handling really 9 large amounts of data ( to my experience 8 when the totals memory consumption of the 7 program approaches something like 1GB) deleting 6 some objects: del largeObject1 del 5 largeObject2 … can give your program 4 the necessary breathing room to function 3 without running out of memory. This can 2 be the easiest way to modify a given program, in 1 case of a “MemoryError” runtime error.

Score: 1

Actually, I just came across a use for this. If 4 you use locals() to return a dictionary 3 of local variables (useful when parsing 2 things) then del is useful to get rid of 1 a temporary that you don't want to return.

More Related questions