Circular (or cyclic) imports in Python

What will happen if two modules import each other?

To generalize the problem, what about the cyclic imports in Python?


There was a really good discussion on this over at comp.lang.python last year. It answers your question pretty thoroughly.

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


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


以上是 Circular (or cyclic) imports in Python 的全部内容, 来源链接: