circular import Module
lycka at carmen.se
Fri Jun 10 14:27:53 CEST 2005
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.
It happens that old Java programmers make one module
per class when they start using Python. That's more
or less equivalent of never using more than 8.3
characters in filenames in modern operating systems,
or to make a detour on your way to work because there
used to be a fence blocking the shortest way a long
time ago... :)
Due to the cycle, you can never use file1 without
file2 or vice versa. Why do you then want it to be
two different modules instead of one?
As others noted, you can usually fix your cycle problems
by importing in a local scope, but just because you can,
it doesn't mean that you should...
More information about the Python-list