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
Use the visualization to inspect how two returned password-generating functions retain access to their enclosing state. section 6.12








