Are reference cycles bad form?

Steven Taschuk staschuk at telusplanet.net
Sat Apr 19 13:16:10 EDT 2003


Quoth Manuel Garcia:
> I would like to ask the group, are reference cycles bad form?
> 
> I am debating whether to give a 'child' object a reference to its
> 'parent' object during creation of the 'child'.

Imho this is an engineering question, not a style question.  It's
a trade-off between the benefits of the algorithms you can write
when the data structure has reference cycles and the slightly
inferior garbage collection properties of such structures.  The
right trade-off to make depends on the circumstances.

For example, if you create and discard structures frequently,
timeliness of collection might make a big difference to the memory
profile of your program.  In such a case, reference cycles are
probably a bad choice.  (In CPython at least, noncyclic structures
are collected by reference counting, which is generally more
timely than the cyclic garbage collector.)

For another, if you need to move rapidly from child to parent,
reference cycles may be a good thing.

There are alternatives, of course.  Perhaps the parent node can be
computed from properties of the child; how fast is that
computation, and how frequently must it be done?

Perhaps the code which needs to move from child to parent can keep
track of the entire list of ancestors from the root to the node
presently of interest; then moving to the parent of the node is
just del ancestors[-1], which is speedy.  How much memory does
that list take?  How many instances of it do you need?  What
should happen if other code moves nodes in the tree while such a
list is being used?

Perhaps you can keep the tree structure in two dicts, one mapping
from parent to a list of its children and one mapping from child
to parent.  How much memory does that take?  Discarding an entire
subtree is more costly in this approach; how often need that be
done?

These are all engineering questions.  Good style in such cases is
imho to use a data structure appropriate to the problem at hand.
Each of the solutions above is suitable in some cases.

  [...]
> Using the 'weakref' module seems silly.  I have complete confidence
> with Python's garbage collection, so why slow things down with extra
> indirection?

Perhaps because reference cycles in which (at least) one link is a
weak reference can be collected by reference counting.  Again,
whether this is a good trade depends on the circumstances.

-- 
Steven Taschuk                               staschuk at telusplanet.net
"[T]rue greatness is when your name is like ampere, watt, and fourier
 -- when it's spelled with a lower case letter."      -- R.W. Hamming





More information about the Python-list mailing list