PEP 8规定:

导入总是放在文件的顶部,就在任何模块注释和文档字符串之后,在模块全局变量和常量之前。

然而,如果我导入的类/方法/函数只在很少的情况下使用,那么在需要时进行导入肯定会更有效吗?

这不是:

class SomeClass(object):

    def not_often_called(self)
        from datetime import datetime
        self.datetime = datetime.now()

比这更有效率?

from datetime import datetime

class SomeClass(object):

    def not_often_called(self)
        self.datetime = datetime.now()

当前回答

以下是对这个问题的最新答案总结 而且 相关的 的问题。

PEP 8 recommends putting imports at the top. It's often more convenient to get ImportErrors when you first run your program rather than when your program first calls your function. Putting imports in the function scope can help avoid issues with circular imports. Putting imports in the function scope helps keep maintain a clean module namespace, so that it does not appear among tab-completion suggestions. Start-up time: imports in a function won't run until (if) that function is called. Might get significant with heavy-weight libraries. Even though import statements are super fast on subsequent runs, they still incur a speed penalty which can be significant if the function is trivial but frequently in use. Imports under the __name__ == "__main__" guard seem very reasonable. Refactoring might be easier if the imports are located in the function where they're used (facilitates moving it to another module). It can also be argued that this is good for readability. However, most would argue the contrary, i.e. Imports at the top enhance readability, since you can see all your dependencies at a glance. It seems unclear if dynamic or conditional imports favour one style over another.

其他回答

当函数被调用0次或1次时,第一种变体确实比第二种更有效。然而,对于第二次和后续调用,“导入每个调用”方法实际上效率较低。请参阅此链接,了解一种通过“惰性导入”将两种方法的优点结合起来的惰性加载技术。

但除了效率之外,还有其他原因可以解释为什么你会更喜欢其中一种。一种方法是让阅读代码的人更清楚地了解这个模块所具有的依赖关系。它们也有非常不同的失败特征——如果没有“datetime”模块,第一个将在加载时失败,而第二个直到方法被调用才会失败。

补充说明:在IronPython中,导入可能比在CPython中要昂贵一些,因为代码基本上是在导入时被编译的。

我不太担心预先加载模块的效率。模块占用的内存不会很大(假设它足够模块化),启动成本可以忽略不计。

在大多数情况下,您希望在源文件的顶部加载模块。对于阅读代码的人来说,它可以更容易地区分哪个函数或对象来自哪个模块。

在代码的其他地方导入模块的一个很好的理由是,如果它在调试语句中使用。

例如:

do_something_with_x(x)

我可以用:

from pprint import pprint
pprint(x)
do_something_with_x(x)

当然,在代码的其他地方导入模块的另一个原因是,如果您需要动态导入它们。这是因为你几乎没有任何选择。

我不太担心预先加载模块的效率。模块占用的内存不会很大(假设它足够模块化),启动成本可以忽略不计。

有趣的是,到目前为止,没有一个回答提到并行处理,当序列化的函数代码被推到其他核心时,可能需要将导入放在函数中,例如在ipyparallel的情况下。

Putting the import statement inside of a function can prevent circular dependencies. For example, if you have 2 modules, X.py and Y.py, and they both need to import each other, this will cause a circular dependency when you import one of the modules causing an infinite loop. If you move the import statement in one of the modules then it won't try to import the other module till the function is called, and that module will already be imported, so no infinite loop. Read here for more - effbot.org/zone/import-confusion.htm

我想提一下我的一个用例,与@John Millikin和@ v.k.提到的用例非常相似:

可选的进口

我使用Jupyter Notebook进行数据分析,我使用相同的IPython Notebook作为所有分析的模板。在某些情况下,我需要导入Tensorflow来做一些快速的模型运行,但有时我工作的地方,Tensorflow没有设置/导入很慢。在这些情况下,我将依赖于tensorflow的操作封装在一个helper函数中,在该函数中导入tensorflow,并将其绑定到一个按钮。

这样,我就可以“重新启动并运行全部”,而不必等待导入,也不必在导入失败时恢复其余的单元格。