Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When am I supposed to use del in python?

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?

like image 259
kpie Avatar asked Aug 31 '16 17:08

kpie


People also ask

What is the use of Del statement?

The del statement can be used to delete an item at a given index. It can also be used to remove slices from a list.

How do you use Del?

The preposition de is translated as "of," "from," or "about," but de also can mean "by," "in," or other prepositions in some cases. Del is simply the contraction of de and the definite article el (not él), so we use del in place of de el.

What is __ del __ in Python?

__del__ is a destructor method which is called as soon as all references of the object are deleted i.e when an object is garbage collected. Syntax: def __del__(self): body of destructor . .

What is difference between Del and pop () in list?

pop() returns deleted value. The del keyword can delete the single value from a list or delete the whole list at a time. At a time it deletes only one value from the list. At a time it deletes only one value from the list.


1 Answers

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.

like image 136
Dmitry Torba Avatar answered Oct 21 '22 11:10

Dmitry Torba