Confusing behavior with python import

Hi there.

I have two files:

<i> a.py:

print('in a') import b print('var') VAR = 1 def p(): print('{}, {}'.format(VAR, id(VAR))) if __name__ == '__main__': VAR = -1 p() bp() # Where does this VAR come from? 

<i> b.py:

 print('in b') import a def p(): ap() 

I do not understand why there are two different VARs that must be the same.

If I transfer the main unit to another file, everything will be fine, i.e. there is only one var.

<i> c.py:

 import a import b if __name__ == '__main__': a.VAR = -1 ap() bp() 

So my question is:

Why do the last two lines of a.py print different results?
Do they not print the same VAR variable in a.py?

By the way, I am using python 2.7 on win7.

Thanks.

+4
source share
1 answer

You might want to read global variables ? Quote:

If a variable is assigned a new value anywhere in the function body, it is assumed that it is local. If a variable is assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as global.

Edit: clarify, here's what happens (for clarity <<20>):

  • The a.py file is a.py .
  • The b.py file b.py imported and, in turn, imports a.py again.
  • Via b import, VAR is defined with a value of 1. This completes the import of b.
  • The __main__ part in a.py runs in its own area; VAR set to -1 there, and p() is executed: this displays -1, since the VAR simply set.
  • Then bp() is executed, which in turn runs ap() . Since the VAR from the point of view of b.py (another area) is still 1, the print statement simply prints 1.

You will also notice that the identifier is different in both print statements: this is because VAR live in a different area and are not connected in any way. They are disabled because __main__ lives in a different anonymous area : the area in which the Python interpreter runs. This is briefly discussed in docs .

+3
source

Source: https://habr.com/ru/post/1382466/


All Articles