+ 2

Python : garbage collector

Is it a good practice to set the variable to None explicitly or it is just another manner to lost the time. I mean : 1. the garbage collector works enough good (no issues was found about in practice) 2. is it not helping to have a more strong code, safe, ..? Many thanks for your opinions and time regards EG

22nd Feb 2021, 12:08 AM
3 Answers
+ 1
I think you need to understand how python manages memory. Each object has a reference counter. For instance a = b will increase the reference counter of the object referenced by 'a'. At the end of a scope, the reference counter is automatically decreased. When the reference counter falls to 0, the memory is immediately freed (it doesn't go through the gc). The garbage collector in python is only used to detect cyclic references and delete them to avoid memory leaks. For instance : class T: pass t = T() t.ref = t # cyclic reference del t Here, the 't' object is not freed directly, because there is a cyclic reference. When the gc will run, it will detect this cyclic reference and free the memory. To avoid cyclic reference, we can use weak references : from weakref import ref class T: pass t = T() t.ref = ref(t) del t Here, memory is freed up directly, because it is a weak reference. As we can see, memory management in Python is very close to memory management in C++ (shared_ptr and weak_tr).
22nd Feb 2021, 8:11 AM
Théophile - avatar
+ 5
Just saying that you have a typo: carbage in the title.
22nd Feb 2021, 1:03 AM
Sonic - avatar
+ 1
To answer your questions : Since memory is freed up directly at the end of the scope for most object, it is totally useless to set a variable explicitly to None. So it is not a good practice, and it is not helping to have a better code at all.
22nd Feb 2021, 8:14 AM
Théophile - avatar