On Sunday, November 12, 2017 at 7:18:04 PM UTC-7, 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)
> 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????

Thanks all for confirming that I was wrong to use "from .. import". Hmmm, 
perhaps for functions it might be okay. But, in most cases it's a lot more 
obvious to use module.function() when calling. Maybe a bit slower, but I'm sure 
it's negligible in most cases.

And, yes, I am trying to share state info between modules. Is this a bad thing? 
I guess I would write getter() and setter() functions for all this. But that 
does seem to remind me too much of some other language :)

Reply via email to