Python导入编码风格 [英] Python import coding style
问题描述
我发现了一种新模式。这种模式是众所周知的,或者是什么意见?
I've discovered a new pattern. Is this pattern well known or what is the opinion about it?
基本上,我有一个很难擦除上下源文件,找出什么模块导入可用,所以现在,而不是
Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of
import foo
from bar.baz import quux
def myFunction():
foo.this.that(quux)
所有我导入到他们实际使用的函数,如下:
I move all my imports into the function where they're actually used., like this:
def myFunction():
import foo
from bar.baz import quux
foo.this.that(quux)
这做了几件事。首先,我很少意外地污染我的模块与其他模块的内容。我可以为模块设置 __ all __
变量,但是我必须随着模块的发展更新它,这不会帮助命名空间污染实际上
This does a few things. First, I rarely accidentally pollute my modules with the contents of other modules. I could set the __all__
variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.
第二,我很少会在模块的顶部结束一系列的导入,一半或更多的我不再需要,因为我' ve重构它。最后,我发现这个模式更容易阅读,因为每个引用的名称是正确的在函数体。
Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it. Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.
推荐答案
之前)顶部投票的回答这个问题是很好的格式,但绝对错了性能。让我演示
The (previously) top-voted answer to this question is nicely formatted but absolutely wrong about performance. Let me demonstrate
import random
def f():
L = []
for i in xrange(1000):
L.append(random.random())
for i in xrange(1000):
f()
$ time python import.py
real 0m0.721s
user 0m0.412s
sys 0m0.020s
b $ b
导入功能体
Import in Function Body
def f():
import random
L = []
for i in xrange(1000):
L.append(random.random())
for i in xrange(1000):
f()
$ time python import2.py
real 0m0.661s
user 0m0.404s
sys 0m0.008s
如您所见,在函数中导入模块可以更高。原因很简单。它将引用从全局引用移动到本地引用。这意味着,至少对于CPython,编译器将发出 LOAD_FAST
指令,而不是 LOAD_GLOBAL
指令。正如顾名思义,这些是更快的。另一个回答者通过在每次循环的每次迭代上导入,人为地膨胀了在 sys.modules
中查找的性能命中。
As you can see, it can be more efficient to import the module in the function. The reason for this is simple. It moves the reference from a global reference to a local reference. This means that, for CPython at least, the compiler will emit LOAD_FAST
instructions instead of LOAD_GLOBAL
instructions. These are, as the name implies, faster. The other answerer artificially inflated the performance hit of looking in sys.modules
by importing on every single iteration of the loop.
通常情况下,最好在顶部导入,但是如果您访问模块很多次,性能是不是。原因是,人们可以更容易地跟踪模块所依赖的内容,并且这样做与Python Universe的大部分其他内容是一致的。
As a rule, it's best to import at the top but performance is not the reason if you are accessing the module a lot of times. The reasons are that one can keep track of what a module depends on more easily and that doing so is consistent with most of the rest of the Python universe.
这篇关于Python导入编码风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!