Python garbage collection and reference counting

I am trying to debug why one of my objects is not collecting garbage, and I have a few questions related to trying to view the documentation / previous questions:

1) If my object is not involved in any reference loops, am I right if garbage collection is not involved and that Python just frees up memory when the object's reference count drops to 0?

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

3) Is Python using sys.getrefcount (obj) to track the number of links?

4) Why does the snapshot below do not 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)) 
+5
source share
1 answer

1) Yes, you are right. You can even disable GC if you are sure that your code does not contain reference loops: https://docs.python.org/2/library/gc.html

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

2) If you want to force create a collection phase, you can just call collect

3) sys.getrefcount (obj) includes a link to a function parameter, not sure if it will answer your question

4) Return get_referrers - this is not a simple list, this is a list with a dictionary containing a link to your object. Try printing a full refund, you will 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 links to your object as elements in the dictionary.

+2
source

Source: https://habr.com/ru/post/1235220/


All Articles