Python global scope troubles

2019-08-06 09:09发布

问题:

I'm having trouble modifying global variables between different files in Python. For example:

File1.py:

x = 5

File2.py:

from File1 import *

def updateX():
    global x
    x += 1

main.py:

from File2 import * 

updateX()
print x #prints 5

回答1:

There are several important things to note here.

First, global isn't global. The really global things, like built-in functions, are stored in the __builtin__ module, or builtins in Python 3. global means module-level.

Second, when you import *, you get new variables with the same names as the ones in the module you import *'d from, referring to the same objects. That means if you then reassign the variable in one module, the other doesn't see the change. On the other hand, mutating a mutable object is a change both modules see.

This means that after the first line of main.py:

from File2 import *

File1, File2, and __main__ (the module the main script runs in) all have separate x variables referring to the same 5 object. File2 and __main__ also have updateX variables referring to the updateX function.

After the second line:

updateX()

Only File2's x variable is reassigned to 6. (The function has a record of where it was defined, so it updates File2's x instead of __main__'s.)

The third line:

print x

prints __main__'s x, which is still 5.