Object cleanup

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed May 30 21:51:52 EDT 2012


On Wed, 30 May 2012 16:56:21 +0000, John Gordon wrote:

> In <6e534661-0823-4c42-8f60-3052e43b7942 at googlegroups.com>
> "psaffrey at googlemail.com" <psaffrey at googlemail.com> writes:
> 
>> How do I force the memory for these soup objects to be freed?
> 
> Have you tried deleting them, using the "del" command?

del doesn't actually delete objects, it deletes names. The object won't 
be deleted until the last name (or other reference) to the object is 
gone. There is no way to force Python to delete an object while it is 
still in use.

Normally you don't notice the difference because most objects only have a 
single reference:

py> class K:
...     def __del__(self):
...             print("Goodbye cruel world!")
...
py> k = K()
py> del k
Goodbye cruel world!


But see what happens when there are multiple references to the object:

py> k = K()
py> x = k
py> y = [1, 2, x, 3]
py> z = {'spam': y}
py> del k
py> del x
py> del y
py> del z
Goodbye cruel world!

The destructor doesn't get called into the last reference is gone.


-- 
Steven



More information about the Python-list mailing list