circular import Module
hancock at anansispaceworks.com
Sat Jun 11 06:23:22 CEST 2005
On Friday 10 June 2005 07:27 am, Magnus Lycka wrote:
> ajikoe at gmail.com wrote:
> > I have two modules (file1.py and file2.py)
> > Is that ok in python (without any weird implication) if my module
> > import each other. I mean in module file1.py there exist command import
> > file2 and in module file2.py 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 __init__.py 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 __init__.py or possibly in
mod1 in order to work correctly), but it's pretty close.
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks http://www.anansispaceworks.com
More information about the Python-list