how to "free" an object/var ?

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Wed Jan 31 02:34:25 EST 2007


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 




More information about the Python-list mailing list