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?
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:
- test imports test2 (h is defined)
- test2 imports test, then it meets the condition.
- 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!