Python import statement in a loop: does import run every loop iteration?
Question: For a code I am writing, I am running `scipy.curve_fit()` tens of thousands of
times. I noticed in the [relevant `curve_fit()` source
code](https://github.com/scipy/scipy/blob/v0.14.0/scipy/optimize/minpack.py),
specifically on [lines
430](https://github.com/scipy/scipy/blob/v0.14.0/scipy/optimize/minpack.py#L430)
and 431 in the source (in the `leastsq()` function), there are two `import`
statements:

    
    
    from numpy.dual import inv
    from numpy.linalg import LinAlgError
    

I call `curve_fit()` inside a loop. I am wondering if the modules loaded by
these `import` 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.

Note: the `import` statements are only called if the `if full_output:`
statement on line 427 of the source code evaluates to true. `full_output=1` is
what is passed to `leastsq()` by `curve_fit()`, so the `import` statements are
indeed called.

Additional note: I am **not asking about importing modules multiple times (so
much)** , 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).

More notes:

    
    
    >>>for x in range(0,1):
    ...     import os
    ... 
    >>> os
    <module 'os' from '/home/lars/env/common/lib64/python2.7/os.pyc'>
    

this works, but if I instead define a function:

    
    
    def a(b):
        if a==True:
           import scipy
    

then

    
    
    for i in range(10):
       a(True)
    scipy
    NameError: name 'scipy' is not defined
    

What is up with that?


Answer: This behavior has nothing to do with a loop, it's all about this funciton. As
doc sais,

> The basic import statement (no from clause) is executed in two steps: find a
> module, loading and initializing it if necessary define a name or names in
> the local namespace for the scope where the import statement occurs.

And funcitons do have their own scope, that's why you can't see imported
module outside of it.

<https://docs.python.org/3/reference/simple_stmts.html#the-import-statement>

