circular references?

James Logajan JamesL at Lugoj.Com
Fri Dec 17 23:35:17 EST 1999


Roy Smith wrote:
> 
> Let's say I've got:
> 
> class a:
>    pass
> 
> class b:
>    def __init__ (self, x):
>       self.x = x
> 
> and then I do:
> 
> foo = a()
> foo.b = b(foo)
> 
> I've now got two objects that contain references to each other.  Is this
> bad?

No. There are many good reasons for using circular references and even more
complex graphs. Use them when it is needed; just remember to clean them up
afterword. Otherwise you may "leak" memory. Proponents of "true" garbage
collection (GC) would point out that Python's reference counting can not
reclaim foo's memory after foo goes out of scope of the execution frame. The
programmer must explicitly set foo.b or foo.b.x to None (or some other
benign value) or "del foo.b" before foo goes out of scope to avoid a leak.
If you are designing your data structures for use in algorithms you
understand, this should not be particularly burdensome. If you find it
burdensome for any reason, then Java or another language with "true" GC may
be the thing to look into.



More information about the Python-list mailing list