Reputation: 10820
I tend to use it whenever I am working on a prototype script, and:
fileCount
), andIn this situation, in order to avoid potential variable clash, I delete the bugger as soon as I am done with it. I know, in a production code I should avoid 1., 2., and 3., but going from a prototype that works to a completely polished class is time consuming. Sometimes I might want to settle for a sub-optimal, quick refactoring job. In that case I find keeping the del
statements handy. Am I developing an unnecessary, bad habit? Is del
totally avoidable? When would it be a good thing?
Upvotes: 30
Views: 6961
Reputation: 70994
I don't think that del
by itself is a code smell.
Reusing a variable name in the same namespace is definitely a code smell as is not using classes and other namespaces where appropriate. So using del
to facilitate that sort of thing is a code smell.
The only really appropriate use of del
that I can think of off the top of my head is breaking cyclic references which are often a code smell as well (and often times, this isn't even necessary). Remember, all del
does is delete the reference to the object and not the object itself. That will be taken care of by either reference counting or garbage collecting.
>>> a = [1, 2]
>>> b = a
>>> del a
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> b
[1, 2]
You can see that the list is kept alive after the del
statement because b
still holds a reference to it.
So, while del
isn't really a code smell, it can be associated with things that are.
Upvotes: 26
Reputation: 21055
Any code that's well organized in functions, classes and methods doesn't need del
except in exceptional circumstances. Aim to build your apps well factored from the start by using more functions and methods, avoid reusing variable names, etc.
The use of a del
statement is OK - it doesn't lead to any trouble, I use it often when I use Python as a replacement for shell scripts on my system, and when I'm making script experiments. However, if it appears often in a real application or library, it is an indication that something isn't all right, probably badly structured code. I never had to use it in an application, and you'd rarely see it used anywhere on code that's been released.
Upvotes: 9