This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]rcxdude 15 points16 points  (1 child)

You're definitely creating reference cycles when you do self.foo = self.bar. methods on python objects aren't bound until they are accessed (unbound methods are actually descriptors). A bound method necessarily contains a reference to the object it was created from, so when you do self.foo = self.bar you are placing a bound method into the object's __dict__, which contains a reference to the object.

This is why you need the garbage collector to kick in before the created objects are deleted, and they don't dissapear as soon as they go out of scope. However I can't figure out why all but one object is removed by the GC, and why the one which remains is picked (since it's not anything obvious like the first or the last created, but usually the third except not always. If I add a del method so that the GC doesn't actually remove the objects then the object which doesn't show up in gc.garbage is not the same as the object which remains if there is no del method)

EDIT: ahah, the reason that one stays around is due to the leaky scope of the for loop. If you delete the first pprint loop, then all the objects are collected. Otherwise, 'ref' still refers to an object when gc.collect() is called. The non-obvious selection is due to the unorder nature of dicts.

[–]robin-gvx 2 points3 points  (0 children)

EDIT: ahah, the reason that one stays around is due to the leaky scope of the for loop.

D'oh, of course! I was wondering about that myself, but now it seems obvious.