-1

Let's say I have 2 python script

the first one:

#X.py
import Y
a = 'list'
print('finish')

and the second one:

#Y.py
import X
z = X.a
print(z)

Question 1:

When I execute X.py first,there's nothing wrong with the code,but when I execute the Y.py first,an error occurs,but why?

Question 2:

I've looked up some answers for circular importing,but I still don't understand.In this case,starting from X.py,the first line is "import Y",then the program should goes to compile Y.py.The first line in Y.py is "import X",so I guess the program goes to X.py again,then goes to Y.py ,and so on..... But why there is no endless loop happens?

Thanks for the help!

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
youngtree
  • 53
  • 6

1 Answers1

1

To answer your first question:

You are getting an AttributeError because when you run Y.py it first executes the import statement which is to import X. Then, when importing X, the import Y statement is executed first in X.py, so the code looks for the variable a in Y.py instead of X.py. You can test this by commenting out import Y in X.py then it will work.

To answer your second question:

A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114