gc module
import gc The gc module provides interfaces to Python’s garbage collector. It allows you to disable automatic collection, manually trigger collection cycles, tune collection thresholds, inspect tracked objects, and debug memory leaks. Since Python uses reference counting as its primary memory management mechanism, the garbage collector supplements it by finding and collecting reference cycles that reference counting cannot handle.
Syntax
import gc
gc.enable()
gc.disable()
gc.isenabled()
gc.collect(generation=2)
gc.set_debug(flags)
gc.get_debug()
gc.get_objects(generation=None)
gc.get_stats()
gc.set_threshold(threshold0, threshold1=10, threshold2=10)
gc.get_count()
gc.get_threshold()
gc.get_referrers(*objs)
gc.get_referents(*objs)
gc.is_tracked(obj)
gc.is_finalized(obj)
gc.freeze()
gc.unfreeze()
gc.get_freeze_count()
Functions
gc.enable()
Enables automatic garbage collection. The collector will run automatically in the background based on the configured thresholds.
Returns: None
gc.disable()
Disables automatic garbage collection. Use this when you need to prevent the collector from interrupting performance-critical code.
Returns: None
gc.isenabled()
Returns whether automatic garbage collection is enabled.
Returns: bool — True if automatic collection is enabled, False otherwise.
gc.collect()
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
generation | int | 2 | The generation to collect (0, 1, or 2). Higher generations include lower generations. |
Performs a garbage collection. Returns the total number of objects collected and uncollectable.
- Generation 0: Young generation objects
- Generation 1: Young generation + incremental old generation (Python 3.14+)
- Generation 2: Full collection of all generations
Returns: int — Sum of collected and uncollectable objects.
gc.set_debug()
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
flags | int | — | Debug flags (see below). Combine with bitwise OR (` |
Sets debug flags for garbage collection. Debug information is written to sys.stderr.
Returns: None
Debug flags:
gc.DEBUG_STATS— Print collection statisticsgc.DEBUG_COLLECTABLE— Print information on collectable objectsgc.DEBUG_UNCOLLECTABLE— Print information on uncollectable objectsgc.DEBUG_SAVEALL— Save unreachable objects ingc.garbageinstead of freeing themgc.DEBUG_LEAK— Equivalent toDEBUG_COLLECTABLE | DEBUG_UNCOLLECTABLE | DEBUG_SAVEALL
gc.get_debug()
Returns the currently set debug flags.
Returns: int — Current debug flags.
gc.get_objects()
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
generation | int or None | None | If specified, return only objects from that generation (0 or 2). |
Returns all objects tracked by the collector. This is useful for debugging memory issues.
Returns: list — List of tracked objects.
gc.get_stats()
Returns per-generation collection statistics since interpreter start.
Returns: list[dict] — List of three dictionaries, one per generation, containing collections, collected, and uncollectable counts.
gc.set_threshold()
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
threshold0 | int | — | Collection trigger for generation 0. Set to 0 to disable collection. |
threshold1 | int | 10 | Controls how much of the old generation is scanned per collection. |
threshold2 | int | 10 | Ignored in Python 3.14+. |
Sets the garbage collection thresholds. When the number of allocations minus deallocations exceeds threshold0, collection starts.
Returns: None
gc.get_count()
Returns the current collection counts for each generation.
Returns: tuple[int, int, int] — Tuple of (count0, count1, count2) representing object counts per generation.
gc.get_threshold()
Returns the current collection thresholds.
Returns: tuple[int, int, int] — Tuple of (threshold0, threshold1, threshold2).
gc.get_referrers()
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
*objs | object | — | One or more objects to find referrers for. |
Returns objects that directly refer to the given objects. Only finds containers that support garbage collection.
Warning: Objects returned may be under construction and in a temporarily invalid state. Use only for debugging.
Returns: list — List of objects referring to the given objects.
gc.get_referents()
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
*objs | object | — | One or more objects to find referents for. |
Returns objects directly referred to by the arguments. Only includes objects visited by the C-level tp_traverse methods.
Returns: list — List of objects directly referred to by the arguments.
gc.is_tracked()
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
obj | object | — | Object to check. |
Returns whether the object is currently tracked by the garbage collector. Atomic types (int, str, etc.) are typically not tracked.
Returns: bool — True if tracked, False otherwise.
gc.is_finalized()
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
obj | object | — | Object to check. |
Returns whether the object has been finalized by the garbage collector.
Returns: bool — True if finalized, False otherwise.
gc.freeze()
Freezes all tracked objects, moving them to a permanent generation that will be ignored in future collections. Useful before fork() to minimize copy-on-write overhead in child processes.
Returns: None
gc.unfreeze()
Unfreezes objects in the permanent generation, moving them back to the oldest generation.
Returns: None
gc.get_freeze_count()
Returns the number of objects in the permanent (frozen) generation.
Returns: int — Count of frozen objects.
Examples
Disable collection during performance-critical operations
import gc
gc.disable()
# Perform operations that create many temporary objects
result = [sum(range(i)) for i in range(10000)]
gc.enable()
Manually trigger collection and inspect results
import gc
# Get object counts before collection
before = gc.get_count()
print(f"Before: {before}")
# Force full collection
collected = gc.collect()
print(f"Collected: {collected} objects")
# Get counts after
after = gc.get_count()
print(f"After: {after}")
Debug memory leaks with gc.get_objects()
import gc
import sys
# Get all tracked objects
all_objects = gc.get_objects()
print(f"Tracked objects: {len(all_objects)}")
# Get only young generation objects
young = gc.get_objects(generation=0)
print(f"Young generation: {len(young)}")
Inspect referrers to find memory leaks
import gc
class Holder:
def __init__(self, value):
self.value = value
# Create an object
data = Holder([1, 2, 3])
# Find what's referencing it
referrers = gc.get_referrers(data)
for ref in referrers:
print(type(ref), getattr(ref, '__name__', ''))
Use debug flags to inspect unreachable objects
import gc
# Enable debug mode to save unreachable objects
gc.set_debug(gc.DEBUG_SAVEALL)
# Create and delete objects with reference cycles
class Node:
def __init__(self, name):
self.name = name
self.next = None
a = Node("a")
b = Node("b")
a.next = b
b.next = a # Reference cycle
del a
del b
# Run collection
gc.collect()
# Inspect garbage
print(f"Unreachable objects: {len(gc.garbage)}")
for obj in gc.garbage:
print(f" {type(obj).__name__}: {obj}")
# Clear garbage
gc.garbage.clear()
Set custom collection thresholds
import gc
# Get current thresholds
current = gc.get_threshold()
print(f"Current thresholds: {current}")
# Set more aggressive collection
gc.set_threshold(500, 5, 5)
# Or disable collection entirely
gc.set_threshold(0)
Common Patterns
Performance tuning
Lower thresholds mean more frequent collection (more CPU, less memory). Higher thresholds mean less frequent collection (less CPU, more memory). The defaults (700, 10, 10) work well for most applications.
# More frequent collection for memory-constrained environments
gc.set_threshold(200, 5, 5)
# Less frequent collection for CPU-constrained environments
gc.set_threshold(2000, 20, 20)
Finding reference cycles
Reference cycles occur when objects reference each other directly or indirectly. The garbage collector handles these, but you can force collection to clean them up:
import gc
# Create a reference cycle
a = []
b = [a]
a.append(b)
del a, b
# Force collection
collected = gc.collect()
print(f"Collected {collected} objects from cycles")
Using callbacks for collection monitoring
import gc
def gc_callback(phase, info):
if phase == "start":
print(f"Starting collection of generation {info['generation']}")
else:
print(f"Collected {info['collected']} objects, "
f"{info['uncollectable']} uncollectable")
gc.callbacks.append(gc_callback)
Errors
ValueError: invalid generation
import gc
gc.collect(generation=3) # ValueError: invalid generation
Valid generations are 0, 1, or 2. Use gc.collect() for full collection.
ReferenceError with gc.garbage
In older Python versions (pre-3.4), manually modifying gc.garbage could cause issues. In modern Python, you can safely clear it after inspection:
gc.garbage.clear() # Safe in Python 3.4+
Warning: get_referrers() returns unstable objects
The objects returned by gc.get_referrers() may be under construction. Only use for debugging, never store references to them:
# Don't do this:
import gc
suspect = some_object
refs = gc.get_referrers(suspect)
stored_refs = refs # Danger: may contain invalid objects