python风格编码,Python导入编码风格

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)

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.

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

Performance

Top Import

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

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

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值