how to "free" an object/var ?

Paddy paddy3118 at netscape.net
Wed Jan 31 12:26:46 EST 2007


On Jan 31, 7:34 am, Steven D'Aprano <s... at REMOVEME.cybersource.com.au>
wrote:
> On Tue, 30 Jan 2007 23:22:52 -0800, Paddy wrote:
> >> As far as I know there is no way to force the deletion of an object
> >> even if it is in use. This is a Good Thing.
>
> >> --
> >> Steven D'Aprano
>
> > The folowing will make the data available for garbage collection no
> > matter what references it:
>
> >>>> l = ["data"] *10
> >>>> l
> > ['data', 'data', 'data', 'data', 'data', 'data', 'data', 'data', 'data',
> > 'data']
> >>>> l2 = l
> >>>> l[:] = []
> >>>> l2
> > []
>
> Sort of.
>
> What happens is that both l and l2 are names referring to the same list.
> After executing l[:] the *contents* of the list change, from lots of
> "data" to nothing. Naturally both l and l2 see the change, because they
> both point to the same list. But the original contents of the list still
> exist until the garbage collector sees that they are no longer in use,
> and then frees them.
>
> You can prove this by doing something like this:
>
> data = "\0"*1000000 # one (decimal) megabyte of data
> L = [data] # put it in a list
> L[:] = []  # "free" the contents of the list
> assert len(data) == 1000000
> # but the megabyte of data still there
>
> Again, you can't force Python to free up memory that is still in use.
> If you could, that would be a bug.
>
> --
> Steven D'Aprano

Thanks Stephen for explaining my answer a bit more.

The [:] = [] trick should be of most use when you go on to allocate
large amounts of data in your program once again, when the gc coud
then make some of the same memory available for the new objects.
As others have said, getting Python to give back memory to the
underlying OS is murder - The best way I have of doing that is to
split your program into two and chain their execution, which allows
the OS to reclaim the memory used by the first Python process when it
finishes.

- Paddy.




More information about the Python-list mailing list