Coping with cyclic imports

Torsten Bronger bronger at
Wed Apr 9 11:36:44 CEST 2008


Jeffrey Froman writes:

> [...]
> Cyclic imports are not a problem by themselves, but cyclic
> definitions are.  Thus:
>         #
>         import b
>         x = 1
>         #
>         import a
>         x = 2
> works fine, but:
>         #
>         import b
>         x = 1
>         #
>         import a
>         x = a.x + 1  # circular definition
> does not.

Okay, thanks, but after some own investigations, I think that the
clever bit is somewhere else.

The above works if you call as the main program, because then is not yet loaded as such when "import a" is executed.  So
gets executed twice, once by "import a", and once after the whole
import thing as the main program.

Actually, there seems to be only one case that is dangerous: If you
import a module cyclicly, it may be that you only get its name
imported but this name points to a yet empty module.  Then, you must
not refer to things in it while the current module itself is
executed.  But you may well refer to things in it from functions or
methods, because they are called much later, when the whole bunch of
modules is already completely loaded and populated.

Consequently, "from a import x" also fails if a is incomplete.

So, the last question is: Under which circumstances does this
happen?  It happens when you import a module which imports (directly
or indictly) the current module and which comes before the current
module in the import order while the program runs.

If you don't rely on imported things at top-level code (but only in
functions and methods which in turn must not be called from the
top-level), everything is fine.

Can anybody confirm that this is correct?


Torsten Bronger, aquisgrana, europa vetus
                                      Jabber ID: bronger at
               (See for further contact info.)

More information about the Python-list mailing list