Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

memory management - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...