Skip to content Skip to sidebar Skip to footer

How Does Circular Import Work Exactly In Python

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 impor

Solution 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 importedprint('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!

Post a Comment for "How Does Circular Import Work Exactly In Python"