Question

If I have the following code:

populationList = []
for i in range(0, 2000)
    populationList.append(myObject).

populationList = []

Would all the objects within populationList get cleaned up now the reference to them has been deleated? I understand that this is the case in Java but it it the same for Python? Or should the objects need to be explicitly deleated?

Was it helpful?

Solution

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.

OTHER TIPS

You do not need to deleate them by yourself. Python has the similar garbage collection with Java. Some further reading material might be: http://www.digi.com/wiki/developer/index.php/Python_Garbage_Collection and https://docs.python.org/2/library/gc.html.

Thanks to @Martijn Pieters: You also be able explicitly disable the gc in Python. BUT should NOT.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top