CPython uses reference counting to automatically clean up objects that are no longer referenced.
Each name, list index, dictionary value or key entry, or attribute is a reference to a Python object, and the interpreter increments and decrements the reference count on each object as needed. When the count reaches 0, objects are automatically cleared from memory.
When you rebind populationList
to a new list object, the reference count for the old list drops to 0 and it is cleared. That in turn clears all references to the contained objects, and they are cleared too, etc.
A garbage collector process also tracks circular references (objects that only reference one another), breaking such cycles automatically as needed. See the gc
module for a tool to introspect and alter the behaviour of the garbage collector.
You can hook into the object de-allocation process by implementing a __del__
method on your custom class. Do read the documentation to learn about the limitations to this hook.
A quick demo:
>>> class Foo:
... def __init__(self, x):
... self.x = x
... def __del__(self):
... print(self.x, 'deleted')
...
>>> populationList = []
>>> for i in range(5):
... populationList.append(Foo(i))
...
>>> populationList = []
4 deleted
3 deleted
2 deleted
1 deleted
0 deleted
Other Python implementations such as Jython and IronPython use different techniques to track objects that can be cleaned up.