Python Forum

Full Version: Reference counting mystery
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
with if True this part will always be executed or in other words else part is NEVER executed
Change the if True to if False to execute the other case.
(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
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.