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_countandsys.getrefcounton a diagnosed case.
Covers
Read
In this order, only the parts listed
0 of 4 done
- Objects and garbage collectionPython language reference
Section 3.1: refcounting with delayed cycle detection; never depend on immediate finalization; close files explicitly
- The cycle collectorgc - cycle garbage collector
collect,get_count,get_threshold,garbageanddisable/enableThe 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. Readgc.get_threshold()on your interpreter before reasoning about generations. - Weak referencesweakref - weak references
Weak-reference objects with callbacks; which types refuse weakrefs; the
WeakValueDictionarypattern - Finding leaksStas' Python Cookbook - selected path
Profiling CPU and Memory: Finding leaks (
gc.collect,gc.garbage) with the refcounting one-liner;tracemallocabove it for sizing
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.getrefcountcounts 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.reffails onlistanddictinstances (subclasses can opt in), ontupleandint, and on slotted classes without__weakref__; sets and frozensets support it. Caches wantWeakValueDictionary, not manual callback books.gc.garbageholds objects the collector refused; an empty list aftergc.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;WeakValueDictionaryor explicit eviction bounds it. - Reading
gc.garbageas the leak list. It holds objects the collector refused; ordinary leaks never appear there.
Try it yourself
Closed-book, before checking anything
__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.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.
a = [];b = [a];a.append(b);del a, b. When is the memory freed?AnswerAt the next cycle collection, not at
del. Refcounts stay positive through the cycle;gc.collect()reclaims both.2.
sys.getrefcount(x)reads 2 for a fresh object at module level but 1 inside a function. Why?AnswerThe 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.
weakref.ref([1, 2, 3])raisesTypeError. Why?Answerlistdoes not support weak references (a subclass oflistdoes). Hold weakref-able objects instead, or useWeakValueDictionaryfor caches.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,garbageanddisable/enable. Use for the cycle-collection and measurement parts of refcounting-gc-weakrefs. - weakref - weak referencesPython Software Foundation · reference
Read weak-reference objects (
refcallbacks,proxyobjects) and theWeakValueDictionaryexample. 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
@dataclassparameters (eq,order,frozen,slots),field()withdefault_factory, frozen instances, post-init processing,replace,asdictandastuple. 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_checkablelimits, Generics forTypeVargenerics, andassert_typefor narrowing checks. Use for theProtocoland narrowing parts of type-hints-protocols; PEP 695 syntax itself is in the language reference.