7

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)) 
1

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! The only thing I'm still not clear on are 2 and 3. If my object has no reference cycles, will gc.collect free the memory if the reference count is zero? Thanks for the clarification on 4. Now I do find that b=a increases the count of referrers...but I get 10 objects and then 11. So when documentation says that memory is freed when the "reference count" drops to 0, what is the right way to get what that reference count is? The last question left is, are you guaranteed that an object with no reference cycles will be freed as soon as the reference count drops to 0?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.