I create many object then I store in a list. But I want to delete them after some time because I create news one and don’t want my memory goes high (in my case, it jumps to 20 gigs of ram if I don’t delete it).
Here is a little code to illustrate what I trying to do:
class test:
def __init__(self):
self.a = "Hello World"
def kill(self):
del self
a = test()
b = test()
c = [a,b]
print("1)Before:",a,b)
for i in c:
del i
for i in c:
i.kill()
print("2)After:",a,b)
A and B are my objects. C is a list of these two objects. I’m trying to delete it definitely with a for-loop in C: one time with DEL and other time with a function. It’s not seem to work because the print continue to show the objects.
I need this because I create 100 000 objects many times. The first time I create 100k object, the second time another 100k but I don’t need to keep the previous 100k. If I don’t delete them, the memory usage goes really high, very quickly.
tl;dr;
are probably the best ways to do this. The rest of this answer tries to explain why some of your other efforts didn’t work.
cpython at least works on reference counting to determine when objects will be deleted. Here you have multiple references to the same objects.
arefers to the same object thatc[0]references. When you loop overc(for i in c:), at some pointialso refers to that same object. thedelkeyword removes a single reference, so:creates a reference to an object in
cand then deletes that reference — but the object still has other references (one stored incfor example) so it will persist.In the same way:
only deletes a reference to the object in that method. One way to remove all the references from a list is to use slice assignment:
Apparently you can also delete the slice to remove objects in place:
This will remove all the references from
mylistand also remove the references from anything that refers tomylist. Compared that to simply deleting the list — e.g.Finally, more recent python revisions have added a
clearmethod which does the same thing thatdel mylist[:]does.