Yukio Usuzumi
Yukio Usuzumi

Reputation: 427

How does circular import work exactly in Python

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

How I expect import to work

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?

Upvotes: 0

Views: 465

Answers (1)

aIKid
aIKid

Reputation: 28292

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!

Upvotes: 1

Related Questions