What are the best practices and recommendations for using explicit del statement in python? I understand that it is used to remove attributes or dictionary/list elements and so on, but sometimes I see it used on local variables in code like this:
def action(x):
result = None
something = produce_something(x)
if something:
qux = foo(something)
result = bar(qux, something)
del qux
del something
return result
Are there any serious reasons for writing code like this?
Edit: consider qux and something to be something “simple” without a __del__ method.
I don’t remember when I last used
del— the need for it is rare indeed, and typically limited to such tasks as cleaning up a module’s namespace after a neededimportor the like.In particular, it’s not true, as another (now-deleted) answer claimed, that
and it’s very important to understand this. To help, let’s make a class with a
__del__and check when it is called:See?
deldoesn’t “make sure” that__del__gets called:delremoves one reference, and only the removal of the last reference causes__del__to be called. So, also:when the last reference does go away (including in ways that don’t involve
del, such as a slice assignment as in this case, or other rebindings of names and other slots), then__del__gets called — whetherdelwas ever involved in reducing the object’s references, or not, makes absolutely no difference whatsoever.So, unless you specifically need to clean up a namespace (typically a module’s namespace, but conceivably that of a class or instance) for some specific reason, don’t bother with
del(it can be occasionally handy for removing an item from a container, but I’ve found that I’m often using the container’spopmethod or item or slice assignment even for that!-).