1

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, specifically on lines 430 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?

NeutronStar
  • 2,057
  • 7
  • 31
  • 49
  • Possible duplicates: http://stackoverflow.com/questions/296036/does-python-optimize-modules-when-they-are-imported-multiple-times, http://stackoverflow.com/questions/12487549/how-safe-is-it-to-import-a-module-multiple-times – ev-br Jun 15 '15 at 14:26
  • @ev-br, those questions are not quite what I am asking. I am essentially asking if modules imported in a loop fall out of scope when the loop iteration ends, or if the code holds on to them. – NeutronStar Jun 15 '15 at 14:35

1 Answers1

1

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

Cassum
  • 319
  • 1
  • 10