Hi, there.
I have two files:
a.py:
print('in a')
import b
print('var')
VAR = 1
def p():
print('{}, {}'.format(VAR, id(VAR)))
if __name__ == '__main__':
VAR = -1
p()
b.p() # Where does this VAR come from?
b.py:
print('in b')
import a
def p():
a.p()
I don’t understand why there’re two different VARs, which is supposed to the same.
If I move the ‘main’ block to another file, everything works well, i.e, there is only one VAR.
c.py:
import a
import b
if __name__ == '__main__':
a.VAR = -1
a.p()
b.p()
So my question is:
Why do the last two lines of a.py print different results?
Don’t they print the same VAR variable in a.py?
BTW, I’m using python 2.7 on win7.
Thanks.
You might want to read up on global variables? To quote:
Edit: to elaborate, here’s what happens (leaving out
c.pyfor clarity):a.pyis executed.b.pyis imported, and in turn importsa.pyagain.VARis defined in with a value of 1. This ends b`s import.__main__part ina.pyis executed in its own scope;VARis set to -1 there, andp()is ran: this displays -1, asVARwas just set to.b.p()is executed, which in turn runsa.p(). BecauseVARfrom the perspective ofb.py(different scope) still has a value of 1, the print statement just outputs 1.You’ll also notice that the id’s are different in both print statements: this is because the
VAR‘s live in a different scope, and are not connected in any way. They are disconnected because__main__lives in a different, anonymous scope: the scope in which the Python interpreter executes. This is briefly discussed in the docs.