Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manual garbage collection in Python

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

like image 779
Casebash Avatar asked Oct 29 '09 05:10

Casebash


People also ask

How do you collect garbage in Python?

Garbage collection is implemented in Python in two ways: reference counting and generational. When the reference count of an object reaches 0, reference counting garbage collection algorithm cleans up the object immediately.

Can we call garbage collector manually?

When there are no more references to an object, the object is finalized and when the Garbage Collection starts these finalized objects get collected this will done automatically by the JVM. We can call garbage collection directly but it doesn't guarantee that the GC will start executing immediately. The java. lang.

What is garbage collector and collect garbage manually?

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically.


2 Answers

Per the docs, gc.get_referrers(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!-).

like image 111
Alex Martelli Avatar answered Oct 06 '22 00:10

Alex Martelli


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.

like image 32
paxdiablo Avatar answered Oct 05 '22 23:10

paxdiablo