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:
self.a = "Hello World"
a = test()
b = test()
c = [a,b]
for i in c:
for i in c:
cpython at least works on reference counting to determine when objects will be deleted. Here you have multiple references to the same objects.
a refers to the same object that
c references. When you loop over
for i in c:), at some point
i also refers to that same object. the
del keyword removes a single reference, so:
for i in c: del i
creates a reference to an object in
c and then deletes that reference -- but the object still has other references (one stored in
c for example) so it will persist.
In the same way:
def kill(self): del self
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:
mylist = list(range(10000)) mylist[:] =  print (mylist)
Apparently you can also delete the slice to remove objects in place:
del mylist[:] #This will implicitly call the `__delslice__` or `__delitem__` method.
This will remove all the references from
mylist and also remove the references from anything that refers to
mylist. Compared that to simply deleting the list -- e.g.
mylist = list(range(10000)) b = mylist del mylist #here we didn't get all the references to the objects we created ... print b #[0, 1, 2, 3, 4, ...]