Unit 9 of 9 · about 2 hours · explain, measure

Reference counts, cycle collection and weak references

Caches and listeners hold objects past their welcome. Lifetime reasoning decides between a leak and a dangling callback.

You'll be able to

  • Explain reference counting and cycle collection, and predict when each frees an object.
  • Use weak references for caches and callbacks without creating ownership bugs.
  • Measure collection behavior with gc.collect, gc.get_count and sys.getrefcount on a diagnosed case.

Covers

Reference counts, cycle collection and weak references
1

Read

In this order, only the parts listed

0 of 4 done

  1. Objects and garbage collectionPython language reference

    Section 3.1: refcounting with delayed cycle detection; never depend on immediate finalization; close files explicitly

  2. The cycle collectorgc - cycle garbage collector

    collect, get_count, get_threshold, garbage and disable/enable

    The generations changed within 3.14: 3.14.0 to 3.14.4 run an incremental collector (gc.get_threshold() reads (2000, 10, 0) on 3.14.4), and the docs record that 3.14.5 restores the three 3.13 generations. Read gc.get_threshold() on your interpreter before reasoning about generations.

  3. Weak referencesweakref - weak references

    Weak-reference objects with callbacks; which types refuse weakrefs; the WeakValueDictionary pattern

  4. Finding leaksStas' Python Cookbook - selected path

    Profiling CPU and Memory: Finding leaks (gc.collect, gc.garbage) with the refcounting one-liner; tracemalloc above it for sizing

2

Focus on

  • CPython frees by refcount immediately and collects cycles later. A self-referencing object with __del__ is still collected since Python 3.4 by PEP 442.
  • sys.getrefcount counts its own argument, and CPython 3.14 borrows references when it loads locals, so one fresh object reads 2 at module level and 1 inside a function. The docs promise nothing beyond 0 or 1; compare readings taken in one context, never absolutes.
  • weakref.ref fails on list and dict instances (subclasses can opt in), on tuple and int, and on slotted classes without __weakref__; sets and frozensets support it. Caches want WeakValueDictionary, not manual callback books.
  • gc.garbage holds objects the collector refused; an empty list after gc.collect() proves the run happened, not that nothing leaked.
Common mistakes · 3
  • Depending on __del__ timing. Collection order is unspecified, so close resources explicitly.
  • Caching instances in a plain dict. The cache owns them forever; WeakValueDictionary or explicit eviction bounds it.
  • Reading gc.garbage as the leak list. It holds objects the collector refused; ordinary leaks never appear there.
3

Try it yourself

Closed-book, before checking anything

Closed-book, build a two-object cycle with a __del__ method and a weakref callback, delete both names, and, with gc.disable() first, show that nothing runs until gc.collect(), which fires the callback and both __del__ methods. Then show sys.getrefcount on a fresh object reads 2 at module level and 1 inside a function on CPython 3.14.4.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.a = []; b = [a]; a.append(b); del a, b. When is the memory freed?Answer

    At the next cycle collection, not at del. Refcounts stay positive through the cycle; gc.collect() reclaims both.

  2. 2.sys.getrefcount(x) reads 2 for a fresh object at module level but 1 inside a function. Why?Answer

    The argument adds a temporary reference, but 3.14 loads locals as borrowed references, so the function call adds none. Only deltas taken in the same context mean anything.

  3. 3.weakref.ref([1, 2, 3]) raises TypeError. Why?Answer

    list does not support weak references (a subclass of list does). Hold weakref-able objects instead, or use WeakValueDictionary for caches.

  4. 4.A slotted class cannot be weak-referenced. What is missing?Answer

    __weakref__ in __slots__. Without that slot the type has no weak-reference support.

You're done when

Your cycle probe frees on collect, your weakref callback fires, and you can state which reference keeps any object alive.

Only when you can do this without notes.

Leads to

Notes

Resources · 4 for this unit, 4 more in the section
  • Stas' Python Cookbook - selected pathStas Bekman · primary

    Run Part I on dictionaries, iteration, functions, closures, decorators, classes and context managers; Part II on modules, files, paths, environment and arguments; and Part IV on versions, dependencies, packaging and code quality. Finish by building one src-layout package from a blank directory.

  • Python language referencePython Software Foundation · required

    Check Data model, Execution model, Import system and Exceptions whenever a claim depends on Python semantics. These pages are the authority when the course and a runtime observation disagree.

  • gc - cycle garbage collectorPython Software Foundation · reference

    Read the cycle collector interface: collect, get_count, garbage and disable/enable. Use for the cycle-collection and measurement parts of refcounting-gc-weakrefs.

  • weakref - weak referencesPython Software Foundation · reference

    Read weak-reference objects (ref callbacks, proxy objects) and the WeakValueDictionary example. Use for the weak-reference part of refcounting-gc-weakrefs.

Also in this section

  • Packaging Python ProjectsPython Packaging Authority · required

    Follow the packaging tutorial once from a blank directory, using a src layout, pyproject.toml, an isolated build and a clean-environment installation test.

  • AlgoMaster Python - structured revisionAlgoMaster · support

    Use Functions, Modules and Packages, OOP, Advanced OOP, Exception Handling, Iterators and Generators, Type Hints and Annotations only after the cookbook pass. Open it for recall practice or a diagnosed weak mechanism, not as a second complete course.

  • dataclasses - data classesPython Software Foundation · reference

    Read the @dataclass parameters (eq, order, frozen, slots), field() with default_factory, frozen instances, post-init processing, replace, asdict and astuple. Use for the validated frozen dataclass in attributes-protocols-dataclasses.

  • typing - type hints and protocolsPython Software Foundation · reference

    Read Protocols for structural typing and runtime_checkable limits, Generics for TypeVar generics, and assert_type for narrowing checks. Use for the Protocol and narrowing parts of type-hints-protocols; PEP 695 syntax itself is in the language reference.