I was wondering what the best way is to use global variables in a multi-script python project. I've seen this question: Using global variables between files? - and while the accepted answer works, the solution seems clunky.
See the below set of scripts. Only main.py is ever called directly; the rest are imported.
First, I've declared my global variables in a separate file:
#global_vars.py
my_string = "hello world"
The main.py
prints the value of the string using a custom function, changes the value of the global variable, and then prints the new value
#main.py
import global_vars
import do_things_module
#Print the instantiated value of the global string
do_things_module.my_function()
#Change the global variable globally
global_vars.my_string = "goodbye"
#Print the new value of the global string
do_things_module.my_function()
do_things_module.py
contains our custom print function, and gets the string straight from the global
#do_things_module.py
import global_vars
def my_function():
print(global_vars.my_string)
Having to keep referencing global_vars.my_string
rather than just my_string
to ensure I'm always reading/writing to the global scoped variable seems long-winded and not very 'pythonic'. Is there a better/neater way?