简体   繁体   中英

confusing behavior with python import

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, ie, 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:

If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'.

Edit: to elaborate, here's what happens (leaving out c.py for clarity):

  1. File a.py is executed.
  2. File b.py is imported, and in turn imports a.py again.
  3. Via b's import, VAR is defined in with a value of 1. This ends b`s import.
  4. The __main__ part in a.py is executed in its own scope ; VAR is set to -1 there, and p() is ran: this displays -1, as VAR was just set to.
  5. Then bp() is executed, which in turn runs ap() . Because VAR from the perspective of b.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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM