variables - Python global scope troubles -
i'm having trouble modifying global variables between different files in python. 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
there several important things note here.
first, global
isn't global. global things, built-in functions, stored in __builtin__
module, or builtins
in python 3. global
means module-level.
second, when import *
, new variables same names ones in module import *
'd from, referring same objects. means if reassign variable in 1 module, other doesn't see change. on other hand, mutating mutable object change both modules see.
this means after first line of main.py
:
from file2 import *
file1
, file2
, , __main__
(the module main script runs in) have separate x
variables referring same 5
object. file2
, __main__
have updatex
variables referring updatex
function.
after second line:
updatex()
only file2
's x
variable reassigned 6
. (the function has record of defined, updates file2
's x
instead of __main__
's.)
the third line:
print x
prints __main__
's x
, still 5.
Comments
Post a Comment