The del
statement has many practical uses to remove attributes and such (see When is del useful in python? and others), but it can also be used to unbind local variables:
def test():
x = ...
del x
Are there any practical use-cases for this?
Garbage collection comes to mind, but x=None
should have the same effect. I've also heard "clean up after import" as a reason, but from ... import ...
does that better. "Cleaner code" has also popped up, but I don't see how del
could make code cleaner (at least for code that isn't in desperate need of a refactoring anyway).
Edit:
This got a bit out of hand. I was expecting an answer such as
"Of course you need del x
! You couldn't do ... properly otherwise, duh!"
I think by now it is fair to say that there is no such answer. If there are uses, then they are coding style related and 'debatable'.
I tried to avoid an 'opinion' discussion by countering the most common ones directly in the question, clearly that didn't work...
I was simply curious why Python has this feature, and thought there might be some best pratice for me to learn.
Since everybody else had a go at their opinion, let me add my own:
I advise against unbinding local variables. Less experienced Python programmers (especially those with a C++ background) are likely to missinterpret del x
as delete the object referenced by x
. They often treat del x
like a short-cut for x.__del__()
. Many use __del__
far too often too. I've seen this misconception many times. What makes it so bad is that it works for them initially! With simple code, where the object is only referenced from that variable, CPython behaves like they think it should. So beginners get positive reinforcement on their misconception and start using it more and more intensively, ending up with a ton of buggy code and weird behaviour that they don't understand.