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

No. 

> test2.py
> from mod1 import myvar, setvar

Be aware that the previous line creates a _local_ "module-
level variable" (in test2.py) named `myvar`, and assigns it
the value of `99`. And also be aware that changes to this
variable will not be reflected in `mod1'. As they are in no
way connected.

However, *SNIFF-SNIFF*, i smell a major flaw in this design.

Why would you create a function to modify a module level
variable anyway? If you want to modify a MLV from another
module (aka: externally), then why not modify it using an
explicit dot path? Observe:

    # from inside an external module
    import mod1
    mod1.myvar = "foo"

Now `myvar` is a string.

So what is the point of this external modification? Are you
attempting to share state between modules?
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to