Module 17 · Advanced Python Concepts — topic 6 of 14
Garbage collection
How unused objects are reclaimed: immediate freeing by reference counting, the cyclic garbage collector, the gc module, weak references, finalizers, and why you should release resources explicitly rather than rely on collection.
Learning objectives
- Explain reference counting and the cycle collector
- Use weak references and finalizers
- Know why resources should be closed explicitly
Definition
Garbage collection is the automatic reclaiming of memory used by objects that are no longer reachable. In CPython, reference counting frees most objects immediately, and a cyclic garbage collector periodically finds groups of objects that only reference each other.
Introduction
You never call free() in Python, yet memory is reused. Most objects vanish the moment they're unused; a few need the garbage collector's help.
Why it matters
Understanding collection explains memory leaks caused by lingering references and cycles, and why with statements matter for files and connections.
Detailed explanation
An object is garbage when no chain of references from running code can reach it.
Reference counting frees an object as soon as its count reaches zero, so most cleanup in CPython is immediate and predictable.
Objects in a reference cycle (a.partner = b; b.partner = a) keep each other's counts above zero. The cyclic collector periodically detects such unreachable groups and frees them.
The gc module controls the collector: gc.collect() runs a full collection, gc.disable() and gc.enable() switch automatic collection off and on, gc.get_count() shows activity.
A weak reference (weakref.ref) refers to an object without keeping it alive; calling it returns the object, or None after it has been collected. Caches use weak references to avoid leaks.
weakref.finalize(obj, func, *args) registers a function to call when obj is collected — more reliable than defining __del__.
Don't rely on garbage collection to release external resources: close files, sockets and connections explicitly with with statements.
Memory leaks in Python usually mean something still references the data — a global list, a cache or an event listener.
Syntax
- Refcounting frees most objects immediately.
- The gc module handles cycles.
- Weak references don't keep objects alive.
Code examples
Freed as soon as unreferenced
deleting cleaned up db after del
Weak references
True None
More examples
Cycles need the collector
after del: cycle still alive a collected collected objects: True
Step-by-step explanation
- After del, no names refer to the nodes, but each node still references the other, so neither count reaches zero.
- With automatic collection disabled, the cycle stays in memory until gc.collect() runs.
- The collector detects the unreachable pair, frees it and triggers the finalizer.
Expected output
Running “Cycles need the collector” prints exactly:
Practical applications
- Caches built with weakref.WeakValueDictionary.
- Diagnosing leaks caused by objects kept in global lists.
Best practices
- Close resources explicitly.
- Avoid unnecessary reference cycles; use weak references for back-links.
- Use gc.collect() for diagnostics, not routine code.
Common mistakes
Relying on __del__ to close resources
Avoid
Prefer
__del__ timing is not guaranteed in every situation; with statements close resources deterministically.
Important notes
- Python 3.14 introduced an incremental cyclic collector that spreads work into smaller steps, reducing pauses.
Key takeaways
- Reference counting frees most objects immediately.
- The cycle collector handles reference cycles.
- Weak references and finalizers observe objects without keeping them alive.
Try it yourself
- 1Build a parent/child tree where children refer back to parents with weak references, and show the tree is freed after del.
- 2Use weakref.WeakValueDictionary to build a cache whose entries disappear when no longer used elsewhere.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- AdvancedWhich objects need CPython's cyclic garbage collector rather than reference counting alone?