Python Interview Questions

32 Questions
Python

Python

Web DevelopmentFrontendBackendData Science

Question 28

How does garbage collection work in Python?

Answer:

Garbage collection in Python is a mechanism for automatically identifying and freeing memory that is no longer in use by the program. Python uses a combination of reference counting and a cyclic garbage collector to manage memory efficiently.

Reference Counting

Python keeps track of the number of references to each object in memory using reference counts. When an object's reference count drops to zero, it means the object is no longer accessible, and the memory it occupies can be reclaimed.

How Reference Counting Works:

  • Incrementing Reference Count: Every time an object is referenced, its reference count is incremented.

    a = [1, 2, 3]  # Reference count for the list [1, 2, 3] is now 1
    b = a          # Reference count is incremented to 2
  • Decrementing Reference Count: Every time a reference to an object is deleted or goes out of scope, its reference count is decremented.

    del a          # Reference count for the list [1, 2, 3] is now 1

When the reference count drops to zero, the memory occupied by the object is immediately deallocated.

Cyclic Garbage Collection

Reference counting alone cannot handle cyclic references, where two or more objects reference each other, forming a cycle. These cycles can prevent the reference count from ever reaching zero, leading to memory leaks.

Python's cyclic garbage collector addresses this issue by periodically searching for groups of objects that reference each other but are not accessible from outside the cycle.

How Cyclic Garbage Collection Works:

  1. Generational Approach: The garbage collector divides objects into three generations. New objects are in the first generation, and objects that survive garbage collection cycles are promoted to the next generation.
  2. Tracking and Collecting Cycles: The garbage collector periodically scans the objects in the younger generations for reference cycles. If a cycle is found and no external references exist, the entire cycle is garbage collected.

Controlling Garbage Collection

The gc module provides an interface to the garbage collector, allowing you to interact with and control the garbage collection process.

Example: Interacting with the Garbage Collector

import gc

# Enable or disable the garbage collector
gc.enable()
gc.disable()

# Force a garbage collection
gc.collect()

# Get garbage collector statistics
print(gc.get_stats())

Example: Circular References and Garbage Collection

import gc

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

# Create two nodes that reference each other
node1 = Node(1)
node2 = Node(2)
node1.next = node2
node2.next = node1

# Break the references to see if garbage collector can collect them
node1 = None
node2 = None

# Force garbage collection
gc.collect()

In this example:

  • Two Node objects are created, each referencing the other.
  • The references are then set to None, breaking the explicit references.
  • The garbage collector is forced to run using gc.collect(), which detects the circular reference and reclaims the memory.

Summary

  • Reference Counting: Python uses reference counting to keep track of the number of references to each object. When an object's reference count drops to zero, it is deallocated.
  • Cyclic Garbage Collection: To handle cyclic references, Python uses a cyclic garbage collector that periodically searches for and collects groups of objects that reference each other but are not accessible from outside the cycle.
  • Generational Approach: The garbage collector divides objects into three generations and focuses on the younger generations for efficiency.
  • Control with gc Module: You can interact with and control the garbage collection process using the gc module.

Understanding how garbage collection works in Python helps you write more efficient code and avoid memory leaks, especially when dealing with complex object relationships.

Recent job openings