Coping with cyclic imports

Duncan Booth duncan.booth at invalid.invalid
Wed Apr 9 06:28:35 EDT 2008


Torsten Bronger <bronger at physik.rwth-aachen.de> wrote:

> 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?

Imports are pretty straightforward really. Just remember the following:

'import' and 'from xxx import yyy' are executable statements. They execute 
when the running program reaches that line.

If a module is not in sys.modules, then an import creates the new module 
entry in sys.modules and then executes the code in the module. It does not 
return control to the calling module until the execution has completed.

If a module does exist in sys.modules then an import simply returns that 
module whether or not it has completed executing. That is the reason why 
cyclic imports may return modules which appear to be partly empty.

Finally, the executing script runs in a module named __main__, importing 
the script under its own name will create a new module unrelated to 
__main__.

Take that lot together and you shouldn't get any surprises when importing 
modules.



More information about the Python-list mailing list