循环导入如何在Python中完全正常工作 [英] How does circular import work exactly in Python

查看:194
本文介绍了循环导入如何在Python中完全正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码(使用CPython 3.4运行):

I have the following code (run with CPython 3.4):

基本上红色箭头解释了我期望导入如何工作:
h在从test2导入之前定义。
因此,当test2导入test1时,它不再是一个空模块(使用h)
而h是test2唯一需要的东西。

Basically the red arrows explain how I expected the import to work: h is defined before importing from test2. So when test2 imports test1 it's not an empty module anymore (with h) And h is the only thing that test2 wants.

我认为这与 http://effbot.org/zone/import-confusion.htm 相矛盾

任何提示?

推荐答案

你缺少的是事实上,来自X import Y 的,不仅仅是导入 Y 。它首先导入模块X 。它在页面中提到:

What you're missing is the fact that from X import Y, does not solely imports Y. It imports the module X first. It's mentioned in the page:


来自X import a,b,c 导入模块X,并创建当前名称空间中对给定对象的引用。换句话说,你现在可以在程序中使用a和b和c。

from X import a, b, c imports the module X, and creates references in the current namespace to the given objects. Or in other words, you can now use a and b and c in your program.

所以,这句话:

from test import h

当达到 h 的定义时不会停止导入。

Does not stop importing when it reaches the definition of h.

让我们更改文件:

test.py

h = 3
if __name__ != '__main__': #check if it's imported
    print('I'm still called!')
...

当您运行 test.py 时,您将获得我' m仍然在错误之前调用!

When you run test.py, you'll get I'm still called! before the error.

条件检查脚本是否已导入。在您编辑的代码中,如果添加条件,只有当它充当主脚本而不是导入的脚本时,才会打印

The condition checks whether the script is imported or not. In your edited code, if you add the condition, you'll print it only when it acts as the main script, not the imported script.

这可以提供帮助:


  1. 测试导入test2(定义为h)

  2. test2导入测试,然后它符合条件。

  3. 条件为false - 导入测试 - ,因此,test2不会查找 test2.j - 它现在还不存在。

  1. test imports test2 (h is defined)
  2. test2 imports test, then it meets the condition.
  3. The condition is false - test is imported -, so, test2 is not going to look for test2.j - it doesn't exist just yet.

希望这会有所帮助!

这篇关于循环导入如何在Python中完全正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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