Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Garbage Collector interface (gc)
Automatic garbage collection is one of the important features of Python. The garbage collector mechanism attempts to reclaim memory occupied by objects that are no longer in use by the program.
Python uses a reference counting mechanism for garbage collection. The Python interpreter keeps count of how many times an object is referenced by other objects. When references to an object are removed, the count for that object is decremented. When the reference count becomes zero, the object's memory is reclaimed.
Normally this mechanism is performed automatically. However, it can be controlled manually if needed. The gc module provides an interface to interact with Python's garbage collector.
Key Functions in gc Module
| Function | Description |
|---|---|
enable() |
Enable automatic garbage collection |
disable() |
Disable automatic garbage collection |
isenabled() |
Returns True if automatic collection is enabled |
collect() |
Run a full collection. Returns number of unreachable objects found |
set_threshold() |
Set the garbage collection thresholds (collection frequency) |
get_threshold() |
Return the current collection thresholds as a tuple |
Basic gc Operations
Let's see how to check and control garbage collection status ?
import gc
# Check if garbage collection is enabled
print("GC enabled:", gc.isenabled())
# Get current thresholds
print("Current thresholds:", gc.get_threshold())
# Manually trigger garbage collection
collected = gc.collect()
print("Objects collected:", collected)
GC enabled: True Current thresholds: (700, 10, 10) Objects collected: 0
Disabling and Enabling Garbage Collection
You can temporarily disable automatic garbage collection for performance-critical sections ?
import gc
print("Initially enabled:", gc.isenabled())
# Disable garbage collection
gc.disable()
print("After disable:", gc.isenabled())
# Re-enable garbage collection
gc.enable()
print("After enable:", gc.isenabled())
Initially enabled: True After disable: False After enable: True
Setting Collection Thresholds
The thresholds control how often garbage collection runs. You can adjust them based on your application's needs ?
import gc
# Get current thresholds
print("Default thresholds:", gc.get_threshold())
# Set new thresholds (generation 0, 1, 2)
gc.set_threshold(1000, 15, 15)
print("New thresholds:", gc.get_threshold())
# Reset to defaults
gc.set_threshold(700, 10, 10)
print("Reset thresholds:", gc.get_threshold())
Default thresholds: (700, 10, 10) New thresholds: (1000, 15, 15) Reset thresholds: (700, 10, 10)
Monitoring Garbage Collection
You can get statistics about garbage collection activity ?
import gc
# Create some objects that form circular references
class Node:
def __init__(self, value):
self.value = value
self.ref = None
# Create circular reference
node1 = Node(1)
node2 = Node(2)
node1.ref = node2
node2.ref = node1
# Delete references
del node1, node2
# Force garbage collection and see what was collected
collected = gc.collect()
print(f"Objects collected: {collected}")
# Get collection statistics
print("GC stats:", gc.get_stats())
Objects collected: 4
GC stats: [{'collections': 89, 'collected': 3234, 'uncollectable': 0}, {'collections': 8, 'collected': 0, 'uncollectable': 0}, {'collections': 0, 'collected': 0, 'uncollectable': 0}]
Use Cases for Manual Garbage Collection
Manual garbage collection control is useful in specific scenarios:
- Performance-critical sections: Disable GC temporarily to avoid interruptions
- Memory cleanup: Force collection after creating many temporary objects
- Debugging: Monitor memory usage and circular references
- Long-running applications: Tune thresholds for optimal performance
Conclusion
The gc module provides fine-grained control over Python's garbage collection. Use gc.collect() to manually trigger cleanup, gc.disable()/gc.enable() to control automatic collection, and gc.set_threshold() to tune collection frequency for your application's needs.
