Garbage collection in Python

Loops | Python Methods and Functions | String Variables

Method for allocating and freeing memory in Python — auto. The user is not required to preallocate or free memory, similar to the dynamic memory allocation used in languages ​​such as C or C++. 
Python uses two strategies for memory allocation:

  • Reference Counting
  • Garbage collection

Prior to Python 2.0, the Python interpreter used reference counting only for memory management. Reference counting works by counting the number of calls to an object by other objects in the system. When object references are removed, the object reference count is decremented. When the reference count goes to zero, the object is freed. former

The literal value 9 is an object. Object 9's reference count is incremented to 1 on line 1. On line 2, its reference count becomes zero when dereferenced. Therefore, the garbage collector releases the object.

A reference loop is created when the reference count of an object cannot be reached. Reference loops, including lists, tuples, instances, classes, dictionaries, and functions, are common. The easiest way to create a reference loop is — create an object that links to itself, as in the example below:

# Literal 9 is an object

b = 9

# Object link count 9
# becomes 0.

b = 4

def create_cycle ():


# create list x

x = []


  # Link loop created

  # here because x contains a link to

  # for yourself.

x.append (x)

create_cycle ()

Since create_cycle () creates an object x that refers to itself, the object x will not be automatically deallocated when the function returns. This will cause the memory that x is using will be held until the Python garbage collector is called.

Ways to make an object garbage collection

x = []

x.append (l)

x.append ( 2 )

# remove the list from memory or
# assign an object x None (Null)


# x = No

The link count for the generated list is now two. However, since it is not available from within Python and cannot be used again, it is considered garbage. In the current version of Python, this list is never freed.

Automatic garbage collection of loops

Since reference loops are computationally intensive to detect, garbage collection must be a scheduled operation. Python schedules garbage collection based on a threshold for object allocation and object deallocation. When the number of allocations minus the number of frees is greater than the threshold, the garbage collector is run. You can check the threshold for new objects (objects in Python known as generation 0 objects) by importing the gc module and querying the garbage collection thresholds:

# loading gc

import gc

# get the current collection
# thresholds as a tuple

print ( "Garbage collection thresholds:" ,

gc.get_threshold ())


 Garbage collection thresholds: (700, 10, 10 ) 

Here the default threshold in the above system is 700. This is begins that when the number of allocations compared to the number of frees exceeds 700, the automatic garbage collector will work. Therefore, any part of your code that frees up large blocks of memory is a good candidate for starting manual garbage collection.

Manual garbage collection

Calling the garbage collector manually during program execution can be a good idea on how to handle the memory consumed by reference loops. 
Garbage collection can be invoked manually as follows:

# Import gc module

import gc

# Returns the count
# of the objects it collected
# and freed

collected = gc.collect ()

# Prints garbage collector
# as 0 object

print ( " Garbage collector: collected " ,

  < code class = "string"> "% d objects." % collected)

If multiple loops are created, then how does manual picking work:

import gc

i = 0  

# create a loop and on each iteration x as a dictionary
# assigned 1

def create_cycle ():

x = {}

  x [i + 1 ] = x

print x

# lists are cleared whenever a full collection or
# highest generation (2) collection started

collected = gc.collect () # or gc.collect (2)

print "Garbage collector: collected% d objects." % (collected)


print " Creating cycles ... "

for i in range ( 10 ):

create_cycle ()


collected = gc.collect ()


print "Garbage collector: collected% d objects." % (collected)


 Garbage collector: collected 0 objects. Creating cycles ... {1: {...}} {2: {...}} {3: {...}} {4: {...}} {5: {...}} {6: {...}} {7: {...}} {8: {...}} {9: {...}} {10: {...}} Garbage collector: collected 10 objects. 

There are two ways to perform manual garbage collection: time-based and event-driven. 
Based at time garbage collection is simple: the garbage collector is called after a fixed interval of time. 
Event garbage collection calls the garbage collector when the event occurs. For example, when the user exits the application, or when the application enters a pending state. 

  • Python Docs

  • Tutorials