circular import Module

Terry Hancock hancock at
Sat Jun 11 06:23:22 CEST 2005

On Friday 10 June 2005 07:27 am, Magnus Lycka wrote:
> ajikoe at wrote:
> > I have two modules ( and
> > Is that ok in python (without any weird implication) if my module
> > import each other. I mean in module there exist command import
> > file2 and in module there exist command import file1?
> Even if it works, it gives you a hint of a design
> problem that might come back and bite you later.
> If file1 depends on file2 *and* vice versa, it seems
> those two modules are tightly coupled. Perhaps they
> should be one module rather than two, or perhaps
> some redesign should be made to untangle this cycle.

True in principle, but what if the resulting module is 1000 lines long?

It doesn't happen often, because python programs don't usually
get that complicated (e.g. lots of tightly interacting classes), but there
are enough exceptions to make it seem desireable to have modules
divided only for readability (i.e. logically the same module).

I can only think of one way to pull this off at present, though,
and that is to create a package:


where looks something like:

from mod1 import *
from mod2 import *
from mod3 import *

Then you treat "big_package" as the module to import.  You'll
still have problems with names that need to be global to all three
modules (I think they'd have to be in or possibly in
mod1 in order to work correctly), but it's pretty close.

Terry Hancock ( hancock at )
Anansi Spaceworks

More information about the Python-list mailing list