Coping with cyclic imports

Torsten Bronger bronger at physik.rwth-aachen.de
Wed Apr 9 11:36:44 CEST 2008


Hallöchen!

Jeffrey Froman writes:

> [...]
>
> Cyclic imports are not a problem by themselves, but cyclic
> definitions are.  Thus:
>
>         # a.py
>         import b
>         x = 1
>
>         # b.py
>         import a
>         x = 2
>
> works fine, but:
>
>         # a.py
>         import b
>         x = 1
>
>         # b.py
>         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 a.py as the main program, because then
a.py is not yet loaded as such when "import a" is executed.  So a.py
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?

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
                                      Jabber ID: bronger at jabber.org
               (See http://ime.webhop.org for further contact info.)



More information about the Python-list mailing list