Python Forum

Full Version: change value of a global variable across all modules
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hello

I wrote a minimum working example showing what I am unable to achieve:

I have a variable in one.py called foo, i would like to change it's value and then use the new value accross all modules

one.py
import two

foo = 'a'

def main():
    two.change_foo()
    print(foo)
    
if __name__ == "__main__":
    main()
two.py
import one

def change_foo():
    print(one.foo)
    one.foo = 'b'
    print(one.foo)
output:
Quote:Reloaded modules: two, one
a
b
a

desired output:
Quote:a
b
b
If you run one.py it is not run as module one but as module __main__. The import one in module two imports a new copy of the execution of one.py. That's why your code doesn't work.
(Dec-31-2018, 01:12 PM)Gribouillis Wrote: [ -> ]If you run one.py it is not run as module one but as module __main__. The import one in module two imports a new copy of the execution of one.py. That's why your code doesn't work.

and how i could solve this? how could i make the import one in module two write a new value in one.py?
https://stackoverflow.com/questions/3536...her-module
it seems to be impossible... how could i to something similar?

edit: this seems to work
one.py:
import two

foo = None

def main():
    print(foo)
    two.change_foo()
    print(two.get_foo())
    
if __name__ == "__main__":
    main()
two.py:
import one

def change_foo():
    one.foo = 'b'

def get_foo():
    return one.foo
better ideas?
You need to distinguish the main program from the library modules that this program imports. These library modules should not need to
import items from the main module. In this case I would define two modules, 'one' and 'two' and write the main program in a separate file
#=========================
# FILE one.py
foo = 'a'

#=========================
# FILE two.py
import one

def change_foo():
    one.foo = 'b'

#=========================
# FILE program.py
import one
import two

def main():
    print(one.foo)
    two.change_foo()
    print(one.foo)

if __name__ == '__main__':
    main()
Alternately, you can set data stored in the main program from imported modules if you pass references to these data to the given modules. For example
# FILE two.py
def change_foo(one): # <- Notice the parameter here. It will be provided by the function's caller
    one.foo = 'b'

#=========================
# FILE program.py
import two

class One:
    foo = 'a'

def main():
    print(One.foo)
    two.change_foo(One)
    print(One.foo)

if __name__ == '__main__':
    main()
thanks i liked the first method and created a file settings.py where i store all this kind of information, i would use this approach also in the future!
Have a good new year :D