Reputation: 438
What I am trying to do is simple, I have a huge dict like so:
class a():
m=0
def __init__(self, m):
self.m = m
def __int__(self):
return self.m
b=a(4)
c=a(6523)
d=a(741)
e=a(84521111)
dict={0:b,1:c,2:e,3:d,4:None,5:None,6:None}
for ele in dict.values():
if ele is not None:
print int(ele)
else:
print "None"
The real one has 4096 elements. Basically, when I decided to kill the object c, I do:
dict[1]=None
Because I don't want to remove the key number 1, and it is working fine, but the object if still alive somewhere and with 4096 objects it can be a problem on my small embedded system. I can check the alive objects with:
import gc
for obj in gc.get_objects():
if isinstance(obj, a):
print obj
Output:
<main.a instance at 0xb749c96c> <main.a instance at 0xb749caac> <main.a instance at 0xb749c9cc> <main.a instance at 0xb749cc0c>
So, how can I delete these object definitely from my memory ?
Nota: del dict[1] doesn't work because it is removed the key as well, same for pop().
I am using Python 2.7, still ...
Upvotes: 0
Views: 92
Reputation: 545
Ensure you're accounting for the fact that they were in memory before you added them to the dictionary.
>>> b=a(4)
>>> c=a(6523)
>>> d=a(741)
>>> e=a(84521111)
>>>
>>> dict={0:b,1:c,2:e,3:d,4:None,5:None,6:None}
>>>
>>> for obj in gc.get_objects():
... if isinstance(obj, a):
... print obj
...
<__main__.a instance at 0x7f4078a34dd0>
<__main__.a instance at 0x7f4078a34d88>
<__main__.a instance at 0x7f4078a34d40>
<__main__.a instance at 0x7f4078a34cf8>
Now delete the originals:
>>> del(b)
>>> del(c)
>>> del(d)
>>> del(e)
>>>
>>> for obj in gc.get_objects():
... if isinstance(obj, a):
... print obj
...
<__main__.a instance at 0x7f4078a34dd0>
<__main__.a instance at 0x7f4078a34d88>
<__main__.a instance at 0x7f4078a34d40>
<__main__.a instance at 0x7f4078a34cf8>
They're still in memory because they're in the dictionary. Now remove them from the dictionary:
>>> dict[3] = None
>>> dict[2] = None
>>>
>>> for obj in gc.get_objects():
... if isinstance(obj, a):
... print obj
...
<__main__.a instance at 0x7f4078a34dd0>
<__main__.a instance at 0x7f4078a34d88>
>>>
We just lost 2 objects with our delete.
Upvotes: 2