Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reference counting mystery
#1
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.
Reply
#2
with if True this part will always be executed or in other words else part is NEVER executed
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Change the if True to if False to execute the other case.
Reply
#4
(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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Shocked An array "mystery": The same array, the same operations but different outcomes mewss 3 2,113 Feb-17-2021, 06:34 PM
Last Post: mewss
  Pass by object reference when does it behave like pass by value or reference? mczarnek 2 2,513 Sep-07-2020, 08:02 AM
Last Post: perfringo
  sorted function example mystery sabaidii2 4 2,482 Feb-10-2020, 09:37 AM
Last Post: DeaD_EyE
  Need some help with a simple syntax mystery kverbeeck 3 2,652 Dec-02-2017, 08:46 PM
Last Post: Windspar
  Help with mystery data paulr 4 4,268 Sep-07-2017, 08:02 AM
Last Post: paulr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020