Structuring Modules with a Ubiquitous Base Class (Circular Dependencies)
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Thu Feb 5 12:16:35 EST 2009
En Wed, 04 Feb 2009 21:12:58 -0200, andrew cooke <andrew at acooke.org>
escribió:
> 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.
>
> 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).
There is no "linking" step in Python, all is done at run time.
Once a module is imported the first time, any subsequent import is very
cheap.
> and i still suspect there is a more efficient metaclass or similar
> approach.
This approach is fine to me.
--
Gabriel Genellina
More information about the Python-list
mailing list