To preface, I think I may have figured out how to get this code working (based on Changing module variables after import), but my question is really about why the following behavior occurs so I can understand what to not do in the future.
I have three files. The first is mod1.py:
# mod1.py
import mod2
var1A = None
def func1A():
global var1
var1 = 'A'
mod2.func2()
def func1B():
global var1
print var1
if __name__ == '__main__':
func1A()
Next I have mod2.py:
# mod2.py
import mod1
def func2():
mod1.func1B()
Finally I have driver.py:
# driver.py
import mod1
if __name__ == '__main__':
mod1.func1A()
If I execute the command python mod1.py
then the output is None
. Based on the link I referenced above, it seems that there is some distinction between mod1.py
being imported as __main__
and mod1.py
being imported from mod2.py
. Therefore, I created driver.py
. If I execute the command python driver.py
then I get the expected output: A
. I sort of see the difference, but I don't really see the mechanism or the reason for it. How and why does this happen? It seems counterintuitive that the same module would exist twice. If I execute python mod1.py
, would it be possible to access the variables in the __main__
version of mod1.py
instead of the variables in the version imported by mod2.py
?