I am familiar with the fact that all import statements in python are executed only once. If reloading is needed, it can be done manually. This has been summarised in this SO answer. However, I am unable to understand the behavior of the following import statements.
I have a config.py
file with the following line:
x = 2
Now, in a python script script_1.py
, I have the following:
import config
import script_2
config.x = 5
script_2.print_config()
config = "foo"
script_2.print_config()
and the script_2.py
goes like this:
import config
def print_config():
print (config)
print (config.x)
Running script_1.py
gives:
<module 'config' from '/Users/xx/config.py'>
5
<module 'config' from '/Users/xx/config.py'>
5
The config.x=5
statement updates the value inside the function script_2
's function (script_2.print_config()
). As explained in user: Fanchen Bao's comment, this behavior is as if config was a global variable.
But for the second call, config
is a string; this time, it does not seem to update the value and script_2.py
still sees it as a module. What am I missing here?