liveBook · Manning

Garbage collection

As explained in Python Workout: 50 ten-minute exercises

Garbage collection is the automatic reclamation of memory occupied by objects that are no longer accessible.

Garbage collection automatically reclaims memory occupied by objects that are no longer accessible. In Python, an object remains available while at least one reference points to it, even after the function that created it returns. section 3.5 section 6.12

Closures make the rule visible: an inner function can keep its enclosing function’s local variables and stack frame alive. Python generally handles this automatically, rather than offering fine-tuned control over collection. section 6.12 section 3.5

Practical consequences include:

  • Deleting a variable or assigning it to another object can trigger an instance’s __del__ method relatively quickly. section 9.15
  • A retained reference can keep objects alive, so apparent function-local state may persist through a returned inner function. section 6.12

Population tracking exercise

Define a Person class with a population class attribute. Increment it for each new instance, then use __del__ to decrement the count when an instance is garbage collected; verify the count after creating and deleting instances. section 9.15

Figure 6.3 Python Tutor’s depiction of two password-generating functions

Use the visualization to inspect how two returned password-generating functions retain access to their enclosing state. section 6.12

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains reference-based lifetime through closures and __del__, but stops short of detailed collector internals or fine-grained control.
Examples
Uses retained closure state, a Python Tutor visualization, and a Person population-count exercise involving __del__.
What you can do after
Diagnose/debug with it by tracing references that keep objects and enclosing function state alive.
How it connects
Connects garbage collection to references, closures, stack frames, and class attributes.

Also explained in

Compare how 9 books explain garbage collection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.