Classes referencing each other

Manuel Bleichner manuel at prolink.de
Fri Sep 1 10:24:01 CEST 2006


Hello list,

I have searched for some time now, but no result...
I'm having the following problem:

In a module I have a huge number of classes of the form:

class A(object):
   connected_to = [B, C]
   <other attributes...>

class B(object)
   connected_to = [C]
   <other attributes...>

class C(object)
   connected_to = [A]
   <other attributes...>

As you see, classes A and B reference classes that
are not yet defined when the class is being defined.
It will raise a NameError: 'B'.

I know i could solve this by leaving out the definition
of 'connected_to' in A and attach it to the class later on by
A.connected_to = [B, C]
but I would like to avoid this, because in the module
there are about 50 classes that have to be altered from time
to time and it's just incredibly ugly if I have to look for
the attribute definitions in more than one place.

Also, I would like to avoid eval(), because the references
have to be followed very often and that would cause more
CPU load and make the program code uglier :)

If anyone of you knows a neat way to solve this, I'd be
very grateful.

Greetings,
Manuel



More information about the Python-list mailing list