Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collection in python and reference counting

I'm trying to debug why one of my objects is not being garbage collected, and I have several questions from trying to go through documentation/previous questions:

1) If my object is not involved in any reference cycles, am I right that garbage collection does not get involved, and that Python simply frees the memory when the object's reference count drops to 0?

2) When the reference count of such a simple object reaches 0, is the memory freed immediately, and if not, is there a way to force it to be freed?

3) Is Python using sys.getrefcount(obj) to keep track of reference counts?

4) Why doesn't the code snippet below increase the number of referrers from 1 to 2 (it prints 1 both times)?

import gc
a = []
print(len(gc.get_referrers(a))
b = a
print(len(gc.get_referrers(a))
like image 992
Dan Avatar asked Nov 04 '15 16:11

Dan


Video Answer


1 Answers

1) Yes, you are right. You can even disable the GC if you're sure your code doesn't contain reference cycles: https://docs.python.org/2/library/gc.html

Since the collector supplements the reference counting already used in Python, you can disable the collector if you are sure your program does not create reference cycles. Automatic collection can be disabled by calling gc.disable().

2) If you want to force the collection stage you can simple call collect

3) sys.getrefcount(obj) includes the reference to parameter of the function, not sure if it answer your question

4) The return of the get_referrers is not a simple list, it's a list with a dictionary containing the reference to your object. Try to print the full return, you'll have something like:

[{'a': [], 'b': [], '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'yourfile.py', '__package__': None, 'gc': <module 'gc' (built-in)>, 'x': {...}, '__name__': '__main__', '__doc__': None}]

You can see all the references to your object as elements in the dictionary.

like image 71
dfranca Avatar answered Sep 29 '22 21:09

dfranca