简体   繁体   English

循环中的 Python 导入语句:导入是否每次循环迭代都运行?

[英]Python import statement in a loop: does import run every loop iteration?

For a code I am writing, I am running scipy.curve_fit() tens of thousands of times.对于我正在编写的代码,我正在运行scipy.curve_fit()数万次。 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:我注意到在相关的curve_fit()源代码中,特别是在源代码中的第 430和 431 (在leastsq()函数中),有两个import语句:

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

I call curve_fit() inside a loop.我在循环内调用curve_fit() 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.我想知道这些import语句加载的模块是否在循环迭代完成后保留,或者模块是否超出范围并且需要在循环的每次迭代中重新加载。

Note: the import statements are only called if the if full_output: statement on line 427 of the source code evaluates to true.注意:只有在源代码第 427 行的if full_output:语句计算结果为真时才会调用import语句。 full_output=1 is what is passed to leastsq() by curve_fit() , so the import statements are indeed called. full_output=1是由curve_fit()传递给leastsq()curve_fit() ,因此确实调用了import语句。

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?这是怎么回事?

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.基本的 import 语句(无 from 子句)分两步执行:找到一个模块,加载并初始化它(如果需要)在本地命名空间中为 import 语句发生的作用域定义一个或多个名称。

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 https://docs.python.org/3/reference/simple_stmts.html#the-import-statement

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM