title: Importing modules: __main__ vs import as module
body: <p>To preface, I think I may have figured out how to get this code working (based on <a href="https://stackoverflow.com/questions/12242417/changing-module-variables-after-import">Changing module variables after import</a>), but my question is really about why the following behavior occurs so I can understand what to not do in the future.</p>
  
  <p>I have three files.  The first is mod1.py:</p>
  
  <pre><code># mod1.py
  
  import mod2
  
  var1A = None
  
  def func1A():
      global var1
      var1 = 'A'
      mod2.func2()
  
  def func1B():
      global var1
      print var1
  
  if __name__ == '__main__':
      func1A()
  </code></pre>
  
  <p>Next I have mod2.py:</p>
  
  <pre><code># mod2.py
  
  import mod1
  
  def func2():
      mod1.func1B()
  </code></pre>
  
  <p>Finally I have driver.py:</p>
  
  <pre><code># driver.py
  
  import mod1
  
  if __name__ == '__main__':
      mod1.func1A()
  </code></pre>
  
  <p>If I execute the command <code>python mod1.py</code> then the output is <code>None</code>.  Based on the link I referenced above, it seems that there is some distinction between <code>mod1.py</code> being imported as <code>__main__</code> and <code>mod1.py</code> being imported from <code>mod2.py</code>.  Therefore, I created <code>driver.py</code>.  If I execute the command <code>python driver.py</code> then I get the expected output: <code>A</code>.  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 <code>python mod1.py</code>, would it be possible to access the variables in the <code>__main__</code> version of <code>mod1.py</code> instead of the variables in the version imported by <code>mod2.py</code>?</p>