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?
答案 0 :(得分:1)
这种行为与循环无关,它与这个功能有关。 作为doc sais,
基本的import语句(no from子句)分两步执行: 找到一个模块,必要时加载并初始化它 在本地名称空间中为import语句的范围定义一个或多个名称。
并且功能确实有自己的范围,这就是为什么你不能在它之外看到导入的模块。
https://docs.python.org/3/reference/simple_stmts.html#the-import-statement