1

I am struggling to understand the following behavior of global variables from a module. I want to import a variable from another module, and change its value through a function call (this is because in my use case that function had to access some other 'private' parts of the module). I know how I can avoid to use globals, I did it, but I am still curious.

First method

This is the preferred method following the python documentation. All globals are put in an external config.py which has to be imported everywhere needed.

#config.py
s = 'initialized'

#module.py
import config

def chg():
    config.s = 'changed'
    prt()

def prt():
    print(config.s)

#main.py
import config
import module

print(config.s)
module.chg()
print(config.s)

This works fine (I also read some threads here about this method) : not only we can access s from other files but it is possible to change its value from everywhere, and this change is "persistent".

guest@desktop /tmp $ python3 main.py 
initialized
changed
changed

Second method

I wasn't clear about whether it was needed or just highly recommended to separated all global stuff into another file.

#module.py
s = 'initialized'

def chg():
    global s
    s = 'changed'
    prt()

def prt():
    print(s)

#main.py
import module

print(module.s)
module.chg()
print(module.s)

Obviously, it is not mandatory. SO this is no magic ;-)

guest@desktop /tmp $ python3 main.py 
initialized
changed
changed

Third method

This is where I am lost. I take the same basis as the second one, but I change the way the global variable is imported.

#main.py
from module import s, chg

print(s)
chg()
print(s)

This does not work any more (I mean, as I expected...).

guest@desktop /tmp $ python3 main.py 
initialized
changed
initialized

So, what am I missing here ? Most of the threads I read were dealing with importing a global variable but not changing its value. Both methods were shown. Thanks !

martineau
  • 119,623
  • 25
  • 170
  • 301
Nicolas Garnier
  • 436
  • 3
  • 9

0 Answers0