from xx import yy

bvdp bob at mellowood.ca
Sun Nov 12 21:17:53 EST 2017


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)

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'.

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????




More information about the Python-list mailing list