Python module import loop issue

Kottiyath n.kottiyath at gmail.com
Tue Dec 30 04:46:50 CET 2008


On Dec 30, 8:24 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Mon, 29 Dec 2008 19:47:51 -0200, Carl Banks <pavlovevide... at gmail.com>  
> escribió:
>
> > On Dec 29, 10:51 am, Kottiyath <n.kottiy... at gmail.com> wrote:
> >> Module Factory:
> >> A1Factory: {'B1Tag':1.1.B1, 'C1Tag':1.2.C1, 'D1Tag':1.3.D1'}
> >> A2Factory: {'B2Tag':2.1.B2, 'C2Tag':2.2.C2, 'D2Tag':2.3.D2'}
>
> >> But, since Module requires objects of B1, C1 etc, it has to import
> >> Factory.
> >> Now, there is a import loop. How can we avoid this loop?
>
> > I'm going to suggest three ways: a straightforward, good-enough way; a
> > powerful, intelligent, badass way; and a sneaky way.
>
> In Python 2.6 (and 3.0) there is a fourth way: class decorators.
>
> > 1. The straightforward, good-enough way
>
> > Define functions in Factory.py called register_A1_subclass and
> > register_A2_subclass, then call them whenever you create a new
> > subclass.
>
> Class decorators are a clean variant of this approach (in my opinion).
>
> > package1/module1.py:
> > -----------------------------
> > import Factory
>
> > class B1(A1):
> >     # define class B1 here
>
> > Factory.register_A1_subclass("B1Tag",B1)
> > -----------------------------
>
> That would become:
>
> @Factory.register_A1_subclass("B1Tag")
> class B1(A1):
>    ...
>
> (for an adequate variant of register_A1_subclass). The advantage is that  
> the "register" stuff appears prominently near the name of the class, and  
> there is no need to repeat the name.
> Also, "B1Tag" can be left out, if it is stored as a class attribute of B1  
> (in some cases using __name__ is enough)
>
> > 2. The powerful, intelligent, badass way
>
> > Metaclasses.  I would guess you do not want to do this, and I wouldn't
> > recommend it if you haven't studied up on how metaclasses work, but
> > it's a textbook example of their usefulness.  If you expect to use
> > factory functions like this a lot, it might be worth your while to
> > learn them.
>
> A problem with metaclasses is when you have intermediate subclasses that  
> are not meant to be registered, but the metaclass applies equally to all  
> of them.
>
> --
> Gabriel Genellina

Hi Gabriel, Carl,
  Thank you very much for your help.
  I never knew about metaclassess and class decorators.  Thank you
again.
  I am actually inclined towards the straightforward way (1). But
still one of the issues that I have mentioned in the first mail
remains. How do I actually hit the code because my entry point is the
EN module.
  Importing every module in EN module so that it hits the code atleast
once is fraught with danger because later, someone might delete it to
clean it up and will start facing issues.
  Could you give me some pointers in such a case?
Regards
K



More information about the Python-list mailing list