title: Python import statement in a loop: does import run every loop iteration?
body: <p>For a code I am writing, I am running <code>scipy.curve_fit()</code> tens of thousands of times.  I noticed in the <a href="https://github.com/scipy/scipy/blob/v0.14.0/scipy/optimize/minpack.py" rel="nofollow">relevant <code>curve_fit()</code> source code</a>, specifically on <a href="https://github.com/scipy/scipy/blob/v0.14.0/scipy/optimize/minpack.py#L430" rel="nofollow">lines 430</a> and 431 in the source (in the <code>leastsq()</code> function), there are two <code>import</code> statements:</p>
  
  <pre><code>from numpy.dual import inv
  from numpy.linalg import LinAlgError
  </code></pre>
  
  <p>I call <code>curve_fit()</code> inside a loop.  I am wondering if the modules loaded by these <code>import</code> statements are kept once an iteration of the loop is completed or if the modules fall out of scope and need to be reloaded in every iteration of the loop.</p>
  
  <p>Note: the <code>import</code> statements are only called if the <code>if full_output:</code> statement on line 427 of the source code evaluates to true.  <code>full_output=1</code> is what is passed to <code>leastsq()</code> by <code>curve_fit()</code>, so the <code>import</code> statements are indeed called.</p>
  
  <p>Additional note: I am <strong>not asking about importing modules multiple times (so much)</strong>, but rather if a module imported in a loop is still accessible by the code after the loop completes (or after each iteration of the loop).</p>
  
  <p>More notes:</p>
  
  <pre><code>&gt;&gt;&gt;for x in range(0,1):
  ...     import os
  ... 
  &gt;&gt;&gt; os
  &lt;module 'os' from '/home/lars/env/common/lib64/python2.7/os.pyc'&gt;
  </code></pre>
  
  <p>this works, but if I instead define a function:</p>
  
  <pre><code>def a(b):
      if a==True:
         import scipy
  </code></pre>
  
  <p>then</p>
  
  <pre><code>for i in range(10):
     a(True)
  scipy
  NameError: name 'scipy' is not defined
  </code></pre>
  
  <p>What is up with that?</p>