I am searching for a method to sharing a global variable across multiple files. I found this and the second answer brought me here. So now I know how to do it. For example:
# config.py
THIS_IS_A_GLOBAL_VARIABLE = 1
# sub.py
import config
def print_var():
print('global variable: ', config.THIS_IS_A_GLOBAL_VARIABLE)
# main.py
import config
from sub import print_var
print_var() # global variable: 1
config.THIS_IS_A_GLOBAL_VARIABLE = 2
print_var() # global variable: 2
This is exactly what I want.
The question is, I am curious that why it works? Here is a simple explanation: Because there is only one instance of each module, any changes made to the module object get reflected everywhere
. But I still don't fully understand it. Is there any further explanation about it?
Very thanks!