On Mon, Nov 13, 2017 at 1:17 PM, bvdp <b...@mellowood.ca> 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) > > 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????
It imports the *value*. What you have is basically this: import mod1 myvar = mod1.myvar setvar = mod1.setvar Since functions remember their contexts, setvar() still sees the globals of mod1. But myvar is a simple integer, so it's basically "myvar = 99". So basically, you can't from-import anything that's going to be changed. You can import constants that way ("from stat import S_IREAD"), or classes/functions (since they're not generally rebound), but as a general rule, don't from-import anything mutable. In fact, if you follow the even-more-general rule of "don't bother with from-imports at all", you'll be right far more than you'll be wrong. ChrisA -- https://mail.python.org/mailman/listinfo/python-list