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()
I do not aspire to provide complete answer, because others have already done this very well. I just want to mention one use case when I find especially useful to import modules inside functions. My application uses python packages and modules stored in certain location as plugins. During application startup, the application walks through all the modules in the location and imports them, then it looks inside the modules and if it finds some mounting points for the plugins (in my case it is a subclass of a certain base class having a unique ID) it registers them. The number of plugins is large (now dozens, but maybe hundreds in the future) and each of them is used quite rarely. Having imports of third party libraries at the top of my plugin modules was a bit penalty during application startup. Especially some thirdparty libraries are heavy to import (e.g. import of plotly even tries to connect to internet and download something which was adding about one second to startup). By optimizing imports (calling them only in the functions where they are used) in the plugins I managed to shrink the startup from 10 seconds to some 2 seconds. That is a big difference for my users.
所以我的答案是否定的,不要总是把导入放在模块的顶部。
我不太担心预先加载模块的效率。模块占用的内存不会很大(假设它足够模块化),启动成本可以忽略不计。
在大多数情况下,您希望在源文件的顶部加载模块。对于阅读代码的人来说,它可以更容易地区分哪个函数或对象来自哪个模块。
在代码的其他地方导入模块的一个很好的理由是,如果它在调试语句中使用。
例如:
do_something_with_x(x)
我可以用:
from pprint import pprint
pprint(x)
do_something_with_x(x)
当然,在代码的其他地方导入模块的另一个原因是,如果您需要动态导入它们。这是因为你几乎没有任何选择。
我不太担心预先加载模块的效率。模块占用的内存不会很大(假设它足够模块化),启动成本可以忽略不计。