I am seeing Python behavior that I don't understand. Consider this layout:
project
| main.py
| test1.py
| test2.py
| config.py
main.py:
import config as conf
import test1
import test2
print(conf.test_var)
test1.test1()
print(conf.test_var)
test2.test2()
test1.py:
import config as conf
def test1():
conf.test_var = 'test1'
test2.py:
import config as conf
def test2():
print(conf.test_var)
config.py:
test_var = 'initial_value'
so, python main.py
produce:
initial_value
test1
test1
I am confused by the last line. I thought that it would print initial_value
again because I'm importing config.py
in test2.py
again, and I thought that changes that I've made in the previous step would be overwritten. Am I misunderstanding something?
When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it. If the named module cannot be found, a ModuleNotFoundError is raised. Python implements various strategies to search for the named module when the import machinery is invoked.
The import statement allows you to import all the functions from a module into your code. Often, though, you'll only want to import a few functions, or just one. If this is the case, you can use the from statement. This lets you import only the exact functions you are going to be using in your code.
The rules are quite simple: the same module is evaluated only once, in other words, the module-level scope is executed just once. If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used.
Use: if "sys" not in dir(): print("sys not imported!")
test2.py
import config as conf
def test2():
print(id(conf.test_var))
print(conf.test_var)
test1.py
import config as conf
def test1():
conf.test_var = 'test1'
print(id(conf.test_var))
Change code like this.
And run main.py
initial_value
140007892404912
test1
140007892404912
test1
So, you can see that in both cases you are changing value of the same variable. See these id
's are same.
Python caches imported modules. The second import
call doesn't reload the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With