tags:

views:

125

answers:

5

Suppose I have code that maintains parent/children structure. In such a structure I get circular references, where child points to parent and parent points to child. Should I worry about them? I'm using Python 2.5.

I am concerned that they will not be garbage collected and the application will eventually consume all memory.

Thanks, Boda Cydo.

+7  A: 

Python will detect the cycle and release the memory when there are no outside references.

Ned Batchelder
+3  A: 

experimentally: you're fine

import itertools

for i in itertools.count():
    a = {}
    b = {"a":a}
    a["b"] = b

consistently stays at using 3.6 MB of RAM

cobbal
Cool! Then I am safe. :)
bodacydo
+2  A: 

Circular references are a normal thing to do, so I don't see a reason to be worried about them. Many tree algorithms require that each node have links to its children and its parent. They're also required to implement something like a doubly linked list.

Colin
Thanks Colin. I didn't know they were "a normal thing." They seemed very special to me. But now I learned otherwise. :)
bodacydo
+1  A: 

I don't think you should worry. Try the following program and will you see that it won't consume all memory:

while True:
    a=range(100)
    b=range(100)
    a.append(b)
    b.append(a)
    a.append(a)
    b.append(b)
douglaz
Thanks for writing this test code. I didn't think of it.
bodacydo
+6  A: 

"Worry" is misplaced, but if your program turns out to be slow, consume more memory than expected, or have strange inexplicable pauses, the cause is indeed likely to be in those garbage reference loops -- they need to be garbage collected by a different procedure than "normal" (acyclic) reference graphs, and that collection is occasional and may be slow if you have a lot of objects tied up in such loops (the cyclical-garbage collection is also inhibited if an object in the loop has a __del__ special method).

So, reference loops will not affect your program's correctness, but may affect its performance and/or footprint.

If and when you want to remove unwanted loops of references, you can often use the weakref module in Python's standard library.

If and when you want to exert more direct control (or perform debugging, see what exactly is happening) regarding cyclical garbage collection, use the gc module in Python's standard library.

Alex Martelli