Python中的循环(或循环)导入 [英] Circular (or cyclic) imports in Python

查看:76
本文介绍了Python中的循环(或循环)导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果两个模块相互导入会发生什么?

What will happen if two modules import each other?

为概括此问题,Python中的循环导入又如何呢?

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

推荐答案

comp.lang.python 去年。


进口真的很简单。只要记住以下内容即可:

Imports are pretty straightforward really. Just remember the following:

import和 from xxx import yyy是可执行语句。当运行的程序到达该行时,它们将执行

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

如果模块不在sys.modules中,则导入将创建新的模块
sys.modules中的条目,然后执行模块中的代码。直到执行完成,它才
将控制权返回给调用模块。

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.

如果sys.modules中确实存在模块,则导入只会返回该
模块是否已完成执行。这就是为什么
循环导入可能返回似乎部分为空的模块的原因。

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.

最后,执行脚本在名为__main__的模块中运行,导入
以自己的名字命名的脚本将创建一个与
__main__无关的新模块。

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中的循环(或循环)导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆