Python module import loop issue

Gabriel Genellina gagsl-py2 at
Tue Dec 30 04:24:58 CET 2008

En Mon, 29 Dec 2008 19:47:51 -0200, Carl Banks <pavlovevidence at>  
> On Dec 29, 10:51 am, Kottiyath <n.kottiy... at> 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 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/
> -----------------------------
> import Factory
> class B1(A1):
>     # define class B1 here
> Factory.register_A1_subclass("B1Tag",B1)
> -----------------------------

That would become:

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

More information about the Python-list mailing list