On this page
  1. gc
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Inspecting Why an Object Is Still Alive (get_referrers)
  7. 2. Freezing Permanent Objects Before fork() (gc.freeze)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Constants & Attributes

gc

Prev: functools | Up: stdlib_module | Next: genericpath
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — gc
Tags: #public #python3 #stdlib


Import

import gc

Overview

Controls CPython's cyclic garbage collector (collect, get_count, get_referrers, get_referents, freeze, disable) that reclaims reference cycles unreachable by reference counting alone. Most Python code never needs to touch gc; reach for it when diagnosing memory leaks, writing weakref tests, or tuning fork-friendly copy-on-write memory (gc.freeze()).

Quick Start

import gc

collected = gc.collect()
counts = gc.get_count()
assert isinstance(collected, int) and len(counts) == 3

Implementation Walkthrough

1. Inspecting Why an Object Is Still Alive (get_referrers)

import gc

class Node:
    pass

holder = [Node()]
referrers = gc.get_referrers(holder[0])
assert holder in referrers

2. Freezing Permanent Objects Before fork() (gc.freeze)

In pre-fork servers (like Gunicorn), call gc.freeze() after loading modules/data so cyclic GC sweeps don't touch shared pages and trigger OS copy-on-write.

Gotchas & Boundaries

Common Functions

Constants & Attributes

Linked from

Related notes