Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the return value of gc.collect() actually mean?

When I do gc.collect() in my Python script, it returns values like 86, 14, etc.

I understand that this call performs garbage collection and I've already gone through the documentation here. But can someone explain through an example what do the numbers actually mean?

like image 283
Sudeep Shukla Avatar asked Apr 14 '18 03:04

Sudeep Shukla


People also ask

What does GC collect return?

Forcing Garbage Collection collect() returns the number of “unreachable” objects it found. In this case, the value is 6 because there are 3 objects with their instance attribute dictionaries.

What does GC collect () do in Python?

Python deletes unwanted objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically frees and reclaims blocks of memory that no longer are in use is called Garbage Collection.

Why we use GC collect?

It performs a blocking garbage collection of all generations. All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to try to reclaim the maximum amount of available memory.

Is it good to call GC collect?

The general advice is that you should not call GC. Collect from your code, but what are the exceptions to this rule? I can only think of a few very specific cases where it may make sense to force a garbage collection.


1 Answers

As you're being chided about for not reading yourself ;-) , it returns "the number of unreachable objects". But the docs aren't really detailed enough to know exactly what that means.

It's really the sum of two numbers: the number of objects that were identified as garbage and actually freed, plus the number of objects that were identified as garbage but could not be freed. For an example of the latter, objects directly involved in unreachable ("garbage") reference cycles containing at least one object with a __del__ method could not be freed automatically before Python 3.4.

Here's an example under Python 3.6.5:

>>> gc.collect() # no trash to begin with
0
>>> a = []
>>> a.append(a) # create an object that references itself
>>> gc.collect()  # but it's not trash because name "a" is bound to it
0
>>> a = None  # break the binding; _now_ it's trash
              # but refcounting alone can't discover that it's trash
>>> gc.collect() # .collect() finds this cyclic trash
1                # and reports that one trash object was collected

In general, there's scant use for this return value.

like image 79
Tim Peters Avatar answered Oct 01 '22 04:10

Tim Peters