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

查看:35
本文介绍了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 去年.它非常彻底地回答了您的问题.

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' 和 '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__ 的模块中,导入以自己的名字命名的脚本将创建一个与以下内容无关的新模块__主要__.

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天全站免登陆