Two files, file1.py, file2.py. Can someone please explain why line 1.8 will print spam == 1 and not spam == 2 ? I've read all python circular import posts but I still don't understand this. Also, I don't understand why file1 is interpreted again from scratch when imported from file2. I was under the impression modules are not loaded again once they've been imported once.
# file1.py
print('1.1: initializing spam to 0')
spam = 0
spam += 1
print('1.4: spam == {}'.format(spam))
print('1.5: importing file2')
import file2
print('1.7: imported file2')
print('1.8: spam == {}'.format(spam)) # why 1 and not 2?
print('FILE 1 PARSED') # why is this executed twice?
# file2.py
print('\t\t\t2.1: importing file1')
import file1
print('\t\t\t2.3: imported file1, file1.spam == {}'.format(file1.spam))
file1.spam += 1
import file1
print('\t\t\t2.6: print from file2: file1.spam == {}'.format(file1.spam))
print('\t\t\tFILE 2 PARSED')
The output I'm getting is this:
1.1: initializing spam to 0
1.4: spam == 1
1.5: importing file2
2.1: importing file1
1.1: initializing spam to 0
1.4: spam == 1
1.5: importing file2
1.7: imported file2
1.8: spam == 1
FILE 1 PARSED
2.3: imported file1, file1.spam == 1
2.6: print from file2: file1.spam == 2
FILE 2 PARSED
1.7: imported file2
1.8: spam == 1
FILE 1 PARSED
PS. I appreciate circular imports are to be avoided, but I need to understand the logic.