How does circular import work exactly in Python

守給你的承諾、 提交于 2019-12-13 04:24:34

问题


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

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.

I think this contradicts with http://effbot.org/zone/import-confusion.htm

Any hints?


回答1:


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:

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.

So, this statement:

from test import h

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

Let's change the file:

test.py

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

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.

Here is something to help:

  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.

Hope this helps!



来源:https://stackoverflow.com/questions/24421658/how-does-circular-import-work-exactly-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!