Classes referencing each other

Georg Brandl g.brandl-nospam at gmx.net
Fri Sep 1 05:50:42 EDT 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.

You could move all connections to a central location after the
class definitions, such as

class A: pass
class B: pass
class C: pass

connections = {A: (B, C), B: (C,), C: (A,)}

Georg



More information about the Python-list mailing list