+ 1

GC.Collect in Python

Can you call the garbage collector explicitly in Python (like C#) 🤔? 👁️

6th Nov 2020, 3:33 PM
Sanjay Kamath
Sanjay Kamath - avatar
5 Réponses
+ 2
I think that it is what 'gc.collect' is supposed to do 😅
6th Nov 2020, 3:48 PM
Théophile
Théophile - avatar
+ 2
import gc gc.collect() # can use ‘del’ as well
6th Nov 2020, 3:49 PM
Flash
+ 1
In fact, python uses a ref counter for each object and when the counter is at 0, the object is immediately freed (it does not go through the gc). However, recursive objects (a list refencing itself) cannot be freed directly, and the role of 'collect' is to find this weird objects and delete them from memory. Exemple : a = [1, 2] del a # the object is deleted immediately a = [] a.append(a) del a # the ref counter is still at 1. 'collect' will find this recursive object and delete it later
6th Nov 2020, 4:06 PM
Théophile
Théophile - avatar
0
Flash why are you talking about 'del'? 🤔
6th Nov 2020, 3:56 PM
Théophile
Théophile - avatar
0
x = [1...] del x # btw it may not free the mem right away, rather schedule a gc call, like dispose() in C# Théophile
6th Nov 2020, 4:01 PM
Flash