Garbage collection does not delete an unreachable object after it is turned off for a while

I have the following hypothetical Python program that uses some functions of the garbage collector ( documentation ):

import gc # Should turn automatic garbage collection off gc.disable() # Create the string a = "Awesome string number 1" # Make the previously assigned string unreachable # (as an immutable object, will be replaced, not edited) a = "Let replace it by another string" # According to the docs, collect the garbage and returns the # number of objects collected print gc.collect() 

The program prints 0 , which seems strange to me because:

  • On first assignment, a str object is created and referenced by a .
  • On the second assignment, the second object str and a and now refers to a .
  • However, the first str object was never deleted, because we turned off automatic garbage collection, so it still exists in memory.
  • Since it exists in memory but is not available, it is similar to the type of object that garbage collection should delete.

I am very grateful for an explanation of why he did not assemble.

PS I know that Python considers some objects (including integers from -3 to 100, as far as I remember) as single, but there are no such specific lines as such objects.

PPS I run it as a whole program, not in the shell

+7
python garbage-collection
source share
1 answer

The gc module in Python is only responsible for collecting circular structures. Simple objects, such as strings, are returned immediately when their reference count becomes 0. gc does not report simple objects, and disabling it does not prevent the recovery of strings.

Additional details: even if the gc module was responsible for the entire restoration of the object, the first line will still not be collected when gc.collect() called, because there is still a live link to this line: the link in the co_consts tuple of the script code object.

+7
source share

All Articles