Search code examples
pythonglobal-variables

python - sharing global variables across files. how it works?


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!


Solution

  • The bit that works is here: config.THIS_IS_A_GLOBAL_VARIABLE = 2

    What is happening is that config is a reference to the module config.py. Then THIS_IS_A_GLOBAL_VARIABLE is one of the attributes in that module and the above assignment make the attribute refer to a different object.

    Now, any other module which has the line: import config refers to the same module and when you fetch any attributes you get hold of the same references.