Structuring Modules with a Ubiquitous Base Class (Circular Dependencies)

andrew cooke andrew at acooke.org
Wed Feb 4 18:12:58 EST 2009


On Feb 4, 7:49 pm, andrew cooke <and... at acooke.org> wrote:
> This leads to a circular dependency - the base class wants to import
> the components, which in turn want to import the base class.
>
> Is there any standard solution to this?

well, to partially answer my own question, this is certainly
possible.  in the general case it might get quite complex, but for the
structure described it is quite simple.  the 'trick' is to import the
component in the *method* of the common base class.

for example:

class Base(object):

    def __init__(self):
        from first import First
        from second import Second
        self.first = lambda *args: First(*args)
        self.second = lambda *args: Second(*args)

where First, defined in first, subclasses Base in the normal way.

however, i suspect this will have a performance hit, since "linking"
is being done at "run time" rather than "compile time".  anyone have
any guidance on how serious that would be?  i guess it could be
ameliorated by doing the work in the constructor (as above, which is
just that way for a compact example - in "real life" the components
are used in a more complex manner).

and i still suspect there is a more efficient metaclass or similar
approach.

andrew



More information about the Python-list mailing list