looking for a pattern
Carlos Ribeiro
cribeiro at mail.inet.com.br
Fri Feb 7 16:14:04 EST 2003
On Friday 07 February 2003 04:55 pm, Geoff Gerrietts wrote:
> Is there a better way to solve this problem that doesn't create a
> cycle, or is the backlink the best bet? For that matter, with the
> advent of the new garbage collection, is it even worth avoiding cycles
> in newer versions of the interpreter?
There is a simple way to fool Python's garbage collector, that is to manage
the backlinks yourself, without using explicit object references. Put all
objects in a list, and then reference the parent using the list index,
instead of the actual object reference. The following example illustrate the
kludge (yes, it is *that* ugly):
# creates a list of person objects
family = [person(dad), person(mom), person(boy)]
# put the links between the elements
family[0].wife = 1
family[0].son = 2
family[1].husband = 0
family[1].son = 2
family[2].father = 0
family[2].mother = 1
You can use the list to hold all objects, or simply use the list to keep a few
auxiliary links, but you got the idea. Of course, you are going to be careful
and do the link management yourself, but this technique allows you to avoid
explicit circular references.
Any other (better) idea?
Carlos Ribeiro
cribeiro at mail.inet.com.br
More information about the Python-list
mailing list