在模块级别还是在功能级别导入? [英] import at module level or at function level?

查看:19
本文介绍了在模块级别还是在功能级别导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种风格更受欢迎?

样式 A:

def foo():
    import some_module
    some_module.something

样式 B:

import some_module

def foo():
    some_module.something

假设 some_module 没有在代码的其他地方使用,只在这个函数内部使用.

Assume that some_module is not used elsewhere in the code, only inside this function.

推荐答案

确实,正如已经提到的,通常最好遵循 PEP 8 建议并在顶部进行导入.不过也有一些例外.理解它们的关键在于您在第二段中嵌入的问题:导入......在什么阶段发生?"

Indeed, as already noted, it's usually best to follow the PEP 8 recommendation and do your imports at the top. There are some exceptions though. The key to understanding them lies in your embedded question in your second paragraph: "at what stage does the import ... happen?"

Import 实际上是一个可执行的语句.导入模块时,模块中的所有可执行语句都会运行.def"也是一个可执行语句;它的执行导致定义的名称与(已经编译的)代码相关联.所以如果你有:

Import is actually an executable statement. When you import a module, all the executable statements in the module run. "def" is also an executable statement; its execution causes the defined name to be associated with the (already-compiled) code. So if you have:

def f():
    import something
    return None

在您导入的模块中,(编译的)导入和返回语句此时与名称f"相关联.当您运行 f() 时,那里的导入语句就会运行.

in a module that you import, the (compiled) import and return statements get associated with the name "f" at that point. When you run f(), the import statement there runs.

如果您推迟导入非常大"或重"的东西,然后您从未运行该函数(在本例中为 f),则导入永远不会发生.这节省了时间(以及一些空间).当然,一旦你真正调用了 f(),导入就会发生(如果 Python 使用缓存的结果已经发生了,但它仍然需要检查),所以你失去了时间优势.

If you defer importing something that is "very big" or "heavy", and then you never run the function (in this case f), the import never happens. This saves time (and some space as well). Of course, once you actually call f(), the import happens (if it has already happened once Python uses the cached result, but it still has to check) so you lose your time advantage.

因此,根据经验,在顶部导入所有内容",直到您完成大量分析并发现导入巨大的东西"在 90% 的运行中浪费了大量时间,而不是节省了其中 10% 的时间很少.

Hence, as a rule of thumb, "import everything at the top" until after you have done a lot of profiling and discovered that importing "hugething" is wasting a lot of time in 90% of your runs, vs saving a little time in 10% of them.

这篇关于在模块级别还是在功能级别导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆