16

So I am curious lets say I have a class as follows

class myClass:
    def __init__(self):
        parts = 1
        to = 2
        a = 3
        whole = 4
        self.contents = [parts,to,a,whole]

Is there any benifit of adding lines

del parts
del to
del a
del whole

inside the constructor or will the memory for these variables be managed by the scope?

kpie
  • 9,588
  • 5
  • 28
  • 50
  • 7
    Nope. The interpreter will automatically free the variables once they're out of scope, i.e. as soon as the constructor returns. `del` is very rarely useful. – Morgan Thrapp Aug 31 '16 at 17:14
  • never, there is a garbage collection – PYPL Aug 31 '16 at 17:15
  • Related: http://stackoverflow.com/questions/34430314/python-lifetime-memory-scope-of-local-variables-inside-a-function – Morgan Thrapp Aug 31 '16 at 17:16
  • 1
    Normally unreachable objects are cleaned up by the interpreter so you do not have to keep track of memory. The only situations where `del` is useful for me are: deleting items from lists, dicts or the like - or when you dont need large objects anymore but they are in a namespace that is going to exist for a long time (eg module-level od in really-long-running-functions). – janbrohl Aug 31 '16 at 17:30
  • `del` may be useful if the algorithm employed by the garbage collection of your Python implementation delays the destruction of out-of-scope objects. E.g., you can read on _PyPy's vs. CPython's_ implementations of garbage collections to see in which instances `del` may become useful (as a rule, very rarely). – boardrider Sep 01 '16 at 13:47

2 Answers2

32

Never, unless you are very tight on memory and doing something very bulky. If you are writing usual program, garbage collector should take care of everything.

If you are writing something bulky, you should know that del does not delete the object, it just dereferences it. I.e. variable no longer refers to the place in memory where object data is stored. After that it still needs to be cleaned up by garbage collector in order for memory to be freed (that happens automatically).

There is also a way to force garbage collector to clean objects - gc.collect(), which may be useful after you ran del. For example:

import gc
a = [i for i in range(1, 10 ** 9)]
...
del a
#  Object [0, 1, 2, ..., 10 ** 9 - 1] is not reachable but still in memory
gc.collect()
#  Object deleted from memory

Update: really good note in comments. Watch for other references to the object in memory. For example:

import gc
a = [i for i in range(1, 10 ** 9)]
b = a
...
del a
gc.collect()

After execution of this block, the large array is still reachable through b and will not be cleaned.

Dmitry Torba
  • 3,004
  • 1
  • 14
  • 24
  • +1, this is a great explanations about the wrong reasons to use `del` on local variables. It would be further improved by also answering the question in the summary, when `del` is *supposed* to be used (e.g. deleting stuff from lists, dicts, deleting attributes...). – user4815162342 Aug 31 '16 at 17:28
  • 9
    An important adjunct to the fact that `del` deletes a reference to a value: if that value has other references besides the one you're deleting, it will live on. So you can't really think of `del` as freeing up memory unless you are certain there are no other references. – kindall Aug 31 '16 at 17:35
8

One use is to delete specific keys from a dictionary.

>>>> food = {"apple": True, "banana": False}
>>>> del food['banana']
>>>> import json
>>>> json.dumps(food)
'{"apple": true}'

I use it all the time for cleaning up dictionaries before converting them to JSON.

Ivan
  • 1,427
  • 1
  • 16
  • 26
  • 1
    @kpie, i ran across this question when googling "what's a good use for del in python", the title for this question seems to conform to that and this answer seems to be a good answer for it. although reading your body i suppose your question really is "should I use `del` inside my class?" would you consider changing the title to be more relevant if that is not your intent? – Rich Apr 28 '20 at 02:04
  • 1
    I wanted to see if deleting keys this way is useful and google sent me here. Good answer. – Mazhar Ali May 19 '21 at 05:26