gr4k gr4k - 3 months ago 16
Python Question

Python import behavior

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?

Answer

Python caches imported modules. The second import call doesn't reload the file.