1

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
Coffee Maker
  • 1,543
  • 1
  • 16
  • 29

1 Answers1

2

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Okay. So what would you suggest as an alternative solution (that doesn't require returning the value from the function)? I don't think Python has pointers or anything like that, so... – Coffee Maker May 29 '14 at 21:02
  • @CoffeeMaker: It's hard to say without a more realistic example. Generally, `import *` and global state should both be avoided. If `File2.py` and `main.py` had both referred to `File1.x`, the problem wouldn't occur. Alternatively, if they had passed the `x` data around through function arguments instead of a global variable, the problem also would have been avoided. – user2357112 May 29 '14 at 21:08