Search code examples
python-3.ximportoverwrite

Behavior of an imported module across multiple files


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?


Solution

  • When config and script_2 are imported in script_1, both config in script_1 and config in script_2 point to the same object: the config module. That's why changes to config.x in script_1 is also seen in script_2. However, these two config are not the same thing. They are two symbols of the same name, living in different namespaces. It just so happens that they point to the same object. It is totally okay for one config to point to something else and that will not affect the other config at all. This is exactly what happens when the config in script_1 is changed to point to a string. This change has no effect on config in script_2.