Python Forum
Reference counting mystery - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Reference counting mystery (/thread-11704.html)



Reference counting mystery - beezergeezer - Jul-22-2018

Consider this code:

import gc

for i in range(10):
    gc.collect()
    if True:
        all_objects = gc.get_objects()
        print "Number of objects =", len(all_objects)
    else:
        print "Number of objects =", len(gc.get_objects())
With the True block, the number of objects increments by 1 on every iteration (except the first). With the False block, it does not. The result of the get_objects function call has one reference (by all_objects), but on the next iteration all_objects gets bound to a new result. At that point, I don't see who is still holding a reference to the first result, so it isn't clear to me why the number of objects keeps climbing. If it is gc itself that is holding a reference, then I don't see what good gc is for debugging a memory leak if it is causing a memory leak itself.

I am running Python 2.7, although I see the same behavior with Python 3.


RE: Reference counting mystery - buran - Jul-22-2018

with if True this part will always be executed or in other words else part is NEVER executed


RE: Reference counting mystery - beezergeezer - Jul-23-2018

Change the if True to if False to execute the other case.


RE: Reference counting mystery - buran - Jul-24-2018

(Jul-23-2018, 10:57 PM)beezergeezer Wrote: Change the if True to if False to execute the other case.
:-) if you change it to False then this part will never be executed. The point is I don't see the reason for using this if-else block if the conditions are fixed True and False


RE: Reference counting mystery - beezergeezer - Jul-24-2018

The reason for the if-else block is to make it easy to run the program once to observe the behavior in one case and then again, after changing the if line, to observe the behavior in the other case.