On 11/12/17 9:17 PM, bvdp wrote:
I'm having a conceptual mind-fart today. I just modified a bunch of code to use 
"from xx import variable" when variable is a global in xx.py. But, when I 
change/read 'variable' it doesn't appear to change. I've written a bit of code to show 
the problem:

mod1.py
myvar = 99
def setvar(x):
     global myvar
     myvar = x

test1.py
import mod1
mod1.myvar = 44
print (mod1.myvar)
mod1.setvar(33)
print (mod1.myvar)

In this case "mod1" is a name in test1 that refers to the mod1 module.  You can access and assign attributes on that module. Anyone else referencing that module (including the module itself) will see those changed attributes.
If this test1.py is run myvar is fine. But, if I run:

test2.py
from mod1 import myvar, setvar
myvar = 44
print (myvar)
setvar(33)
print (myvar)

It doesn't print the '33'.

In this case, "myvar" is a name that references the same value as mod1.myvar.  Now both myvar and mod1.myvar refer to the same value. There is no direct connection between the myvar name and the mod1.myvar name.  When you reassign myvar, it now refers to some other value. mod1.myvar is unaffected.

--Ned.
I thought (apparently incorrectly) that import as would import the name myvar 
into the current module's namespace where it could be read by functions in the 
module????


--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to