在Python中循环(或循环)导入

如果两个模块导入对方会发生什么?

为了概括问题,Python中的循环导入呢?

最佳答案
去年在comp.lang.python有一个很好的讨论。它很好地回答了你的问题。

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.

转载注明原文:在Python中循环(或循环)导入 - 代码日志