views:

199

answers:

5

Is there any way to manually remove an object which the garbage collection refuses to get rid of even when I call gc.collect()? Working in Python 3.0

A: 

It depends on what your Python is running on. Here's good article that explains the details

Quoting:

In current releases of CPython, each new assignment to x inside the loop will release the previously allocated resource. Using GC, this is not guaranteed. If you want to write code that will work with any Python implementation, you should explicitly close the resource; this will work regardless of GC:

for name in big_list:
    x = Resource()
    do something with x
    x.close()
DroidIn.net
+1  A: 

If the GC is refusing to destroy it, it's because you have a reference to it somewhere. Get rid of the reference and it will (eventually) go. For example:

myRef = None

Keep in mind that GC may not necessarily destroy your object unless it needs to.

If your object is holding resources not under the management of Python (e.g., some trickery with C code called from Python), the object should provide a resource release call so you can do it when you want rather than when Python decides.

paxdiablo
A: 

del Or None are your only friends

>>> a = "Hello"
>>> a = None
Or
>>> del a
Tzury Bar Yochay
Not necessarily true. The object just needs to be unreachable (or have an agreeably disposable ref-count, which very hopefully agrees with the former) to be eligible for reclamation.
pst
`del a` doesn't delete the object (just a note; not implying that you imply that)
hasen j
+8  A: 

Per the docs, gc.getreferrers(thatobject) will tell you why the object is still alive (do it right after a gc.collect() to make sure the undesired "liveness" is gonna be persistent). After that, it's somehow of a black art;-). You'll often find that some of the referrers are lists (so WHY is that list referring to thatobject? you can .remove it in an emergency mode, but making the normal code sound is better...), and, even more often, dicts (many of whose may be __dict__s of some class instance or other -- often not trivial to find out which one... again, brute-force removal is sometimes an expedient emergency solution, but never a sustainable long-range one!-).

Alex Martelli
+2  A: 

When there are no references to your variable you can just go:

import gc
gc.collect()

This will run garbage collection on all objects.

Gerald Kaszuba
"Is there any way to manually remove an object **which the garbage collection refuses to get rid of** in Python?"
musicfreak
I actually wasn't 100% clear. Clarified now.
Casebash