Search code examples
pythonimportglobal

Python when are imported files evaluated?


I hope the question phrasing is meaningful. What I am wanting to do is change a flat variable's value in a file, and have the files which have imported that file see the updated value. It appears that I can do this. For example:

#settings.py
VARIABLE = 1
def change_variable():
    global VARIABLE
    VARIABLE = 2

and

#main.py
import settings
print(settings.VARIABLE)
settings.change_variable()
print(settings.VARIABLE)

which outputs:

1
2

As desired. Although I was a little surprised since I thought maybe the value of settings.VARIABLE would be fixed after settings was imported. I would like to know whether I can rely on this behaviour. My question is thus also, when in general will the values from an imported file be "updated" or "re-evaluated" from the perspective of the importing file? How does it work behind the scenes?

I could of course just make a class. But I don't like the idea of settings, or any config, being an object. I prefer it flat. But I want the option to change the settings after import based on user cli input.


Solution

  • Once the file settings.py is imported, python is done looking at the file. It now has a module loaded in memory, and if it is imported somewhere else, that module will be loaded there. The file is never looked at again after the first import.

    Your function changed the value of VARIABLE in that module. You can depend on it being your new value unless you change it again.