deleting objects present in a list

Chris Rebert clp2 at rebertia.com
Tue Apr 20 18:23:20 EDT 2010


> On Apr 20, 8:44 pm, Terry Reedy <tjre... at udel.edu> wrote:
>> On 4/20/2010 3:21 PM, Sandy wrote:
>> > Hi all,
>> > I have large number of objects created and to handle them properly, I
>> > store them in a list. How can I delete all of these objects (delete I
>> > mean here is to remove the object from memory not just from list)?
>> > I cannot use the list to iterate through the objects to delete them.
>> > Because 'del' only reduces the reference count and as it is present in
>> > the list it is not deleted. I cannot delete the list because I loose
>> > control over the objects.
>>
>> Deleting the list is the best you can do. If that deletes the last
>> reference, then the interpreter will delete the object when it feels
>> like it. For *current* CPython, this will be immediately. For other
>> implementations, whenever.

On Tue, Apr 20, 2010 at 3:10 PM, Sandy <dksreddy at gmail.com> wrote:
<snip>
> What does 'immediately' mean? I did a small test and here are the
> results.
>
> import psutil
>
> def testing():
>    class Object():
>        pass
>
>    l = {}
>    apm = psutil.avail_phymem()/(1024*1024)
>    print 'Before creating objs: ' + repr(apm)
>
>    for i in xrange(500000):
>        l.update({Object():1})
>
>    apm = psutil.avail_phymem()/(1024*1024)
>    print 'After creating objs: ' + repr(apm)
>    return l
>
> def hello():
>    myl = testing()
>
>    apm = psutil.avail_phymem()/(1024*1024)
>    print 'Before deleting: ' + repr(apm)
>
>    del myl
>
>    # Here I want to delete the objects in the list
>    # deleting myl doesn't seem to change the memory
>
>    apm = psutil.avail_phymem()/(1024*1024)
>    print 'After deleting: ' + repr(apm)
>
>
> if __name__ == '__main__':
>    hello()
>
> OUTPUT:
> Before creating objs: 2516L
> After creating objs: 2418L
> Before deleting: 2418L
> After deleting: 2430L
>
> In my original case the memory is not getting released even after long
> time.

Python does *delete* the objects, but makes no guarantees regarding
*returning memory* to the OS.
CPython holds onto the now-unused memory for a while so it's not
constantly thrashing and/or fragmenting memory by malloc()-ing some
and then free()-ing [some of] it right back.

I'm unsure if there's a way to force Python to actually free() unused
memory back to the OS.

Cheers,
Chris
--
Please don't top-post!
http://blog.rebertia.com



More information about the Python-list mailing list