Classes referencing each other

John Machin sjmachin at
Fri Sep 1 12:05:21 CEST 2006

Manuel Bleichner wrote:
> 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.

So why can't you do it all in one place by
    A.connected_to = [B, C]
    B.connected_to = [C]
    C.connected_to = [A]

or by a tabular method:

connections = (
    (A, [B, C]),
    (B, [C]),
    (C, [A]),
for cls_from, targets in connections:
    # maybe insert some checking code in here ...
    # is X.connected_to = [X] allowed?
    # is Y.connected_to = [] allowed?
    cls_from.connected_to = targets

> 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 :)

Avoiding eval() does always seem to be a good thing :-)

BTW, care to tell us what the connections mean? Applications of
connected instances of the one class are of course very common, but 50
classes connected in a cyclic fashion is rather new to me ...


More information about the Python-list mailing list