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

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

问题描述

哪种风格更可取?

样式A:

$ p $ def foo():
import some_module
some_module.something

样式B:

  import some_module 
$ b $ def foo():
some_module.something

假设代码中没有使用 some_module ,只能在这个函数内部使用。

解决方案

事实上,正如已经指出的那样,通常最好遵循PEP 8的建议并在顶部进行导入。虽然有一些例外。理解它们的关键在于你的第二段中的嵌入式问题:导入......在什么阶段发生?

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

  def f():
import something
return None

在您导入的模块中,(编译的)导入和返回语句与名称f关联点。当您运行 f()时,会运行import语句。



如果您推迟导入非常大或沉重 ,然后你永远不会运行该函数(在这种情况下,f),导入从不发生。这节省了时间(以及一些空间)。当然,一旦你真的调用了f(),导入就会发生(如果它已经发生,一旦Python使用缓存的结果,但它仍然需要检查),所以你失去了时间上的优势。



因此,作为一个经验法则,将所有内容导入顶部直到完成了大量分析后发现导入巨大会浪费大量时间在90%的运行中,与其中10%节省一点时间。


Which style is preferable?

Style A:

def foo():
    import some_module
    some_module.something

Style B:

import some_module

def foo():
    some_module.something

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

解决方案

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

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.

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.

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天全站免登陆