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()

当前回答

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

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

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

其他回答

为了完成老谋子的回答和最初的问题:

当我们不得不处理循环依赖关系时,我们可以做一些“技巧”。假设我们正在处理模块a.py和b.py,它们分别包含x()和b.y()。然后:

我们可以移动模块底部的from导入之一。 我们可以将其中一个from导入移动到实际需要导入的函数或方法中(这并不总是可行的,因为您可能从多个地方使用它)。 我们可以把其中一个import改成import,就像import a

总结一下。如果您没有处理循环依赖关系,也没有使用某种技巧来避免它们,那么最好将所有导入放在顶部,因为原因已经在这个问题的其他答案中解释过了。请在做这些“技巧”时附上评论,这总是受欢迎的!:)

Curt提出了一个很好的观点:第二个版本更清晰,并且会在加载时失败,而不是在加载后失败,而且出乎意料。

通常我不担心加载模块的效率,因为它(a)非常快,(b)大多数只发生在启动时。

如果你不得不在意想不到的时候加载重量级模块,使用__import__函数动态加载它们可能更有意义,并确保捕获ImportError异常,并以合理的方式处理它们。

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

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.

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

模块导入非常快,但不是即时的。这意味着:

将导入放在模块的顶部是可以的,因为这是一个微不足道的成本,只需要支付一次。 将导入放在函数中会导致对该函数的调用花费更长的时间。

所以如果你关心效率,把进口放在最上面。只有在分析显示有帮助的情况下,才将它们移动到函数中(您进行了分析,以查看哪里可以最好地提高性能,对吗??)


我所见过的执行惰性导入的最佳理由是:

可选的库支持。如果您的代码有多个使用不同库的路径,如果没有安装可选库,请不要中断。 在插件的__init__.py中,该插件可能被导入,但实际上没有使用。例如Bazaar插件,它们使用bzrlib的惰性加载框架。