CPython releases many objects through reference counting. The gc module complements it by detecting cycles, such as two unreachable objects that still reference each other.

Practical example

import gc

before = gc.get_count()
unreachable = gc.collect()
after = gc.get_count()

print("collections counters:", before, "->", after)
print("unreachable objects:", unreachable)

What the counters mean

get_count() exposes internal allocation counters since collection in each generation. They are not memory usage. Use get_stats() for collection statistics and a tool such as tracemalloc to trace allocations.

Diagnose without distorting production

Enable gc.DEBUG_SAVEALL only in a controlled environment: it retains found objects in gc.garbage and can increase memory use. Remove references created by the investigation itself.

When tuning is justified

Disabling collection or changing thresholds may reduce pauses in a specific workload, but it also delays cycle cleanup. Measure latency and memory in the real process before making that tradeoff.

Keep learning

Strengthen the foundation with Python logging. The official Python documentation, accessed July 22, 2026, documents the API, limitations, and version differences.