0

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?

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

3 Comments

ok I did more test. I changed all from ... import ... to import, and in test.py: import test2 if __name__ == '__main__': print(test2.j) this will work, but without the if condition check it will raise AttributeError. What's the difference?
It's just like the article says.
That definitely helps! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.