Python 中的本地导入语句 [英] Local import statements in Python

查看:39
本文介绍了Python 中的本地导入语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为将 import 语句放在靠近使用它的片段的位置,通过使其依赖关系更加清晰来提高可读性.Python 会缓存这个吗?我应该关心吗?这是个坏主意吗?

I think putting the import statement as close to the fragment that uses it helps readability by making its dependencies more clear. Will Python cache this? Should I care? Is this a bad idea?

def Process():
    import StringIO
    file_handle=StringIO.StringIO('hello world')
    #do more stuff

for i in xrange(10): Process()

再说明一点:它适用于使用库的神秘位的方法,但是当我将该方法重构到另一个文件中时,我没有意识到我错过了外部依赖,直到出现运行时错误.

A little more justification: it's for methods which use arcane bits of the library, but when I refactor the method into another file, I don't realize I missed the external dependency until I get a runtime error.

推荐答案

其他答案对 import 的实际工作方式有轻微的混淆.

The other answers evince a mild confusion as to how import really works.

本声明:

import foo

大致相当于这个语句:

foo = __import__('foo', globals(), locals(), [], -1)

也就是说,它在当前作用域中创建一个与请求的模块同名的变量,并将调用 __import__() 的结果分配给它,使用该模块名称和一大堆默认参数.

That is, it creates a variable in the current scope with the same name as the requested module, and assigns it the result of calling __import__() with that module name and a boatload of default arguments.

__import__() 函数在概念上处理将字符串 ('foo') 转换为模块对象.模块缓存在 sys.modules 中,这是 __import__() 查找的第一个位置——如果 sys.modules 有 'foo',这就是 __import__('foo') 将返回的内容,无论它是什么.它真的不在乎类型.你可以亲眼看到这一点;尝试运行以下代码:

The __import__() function handles conceptually converts a string ('foo') into a module object. Modules are cached in sys.modules, and that's the first place __import__() looks--if sys.modules has an entry for 'foo', that's what __import__('foo') will return, whatever it is. It really doesn't care about the type. You can see this in action yourself; try running the following code:

import sys
sys.modules['boop'] = (1, 2, 3)
import boop
print boop

暂时搁置文体问题,在函数中使用 import 语句即可满足您的需求.如果模块之前从未被导入,它会被导入并缓存在 sys.modules 中.然后它将模块分配给具有该名称的局部变量.它不是不是修改任何模块级状态.它确实可能会修改一些全局状态(向 sys.modules 添加一个新条目).

Leaving aside stylistic concerns for the moment, having an import statement inside a function works how you'd want. If the module has never been imported before, it gets imported and cached in sys.modules. It then assigns the module to the local variable with that name. It does not not not modify any module-level state. It does possibly modify some global state (adding a new entry to sys.modules).

也就是说,我几乎从不在函数中使用 import.如果导入模块会显着降低您的程序速度——比如它在静态初始化中执行了长时间的计算,或者它只是一个庞大的模块——并且您的程序实际上很少需要该模块来做任何事情,那么只在内部导入就完全没问题了使用它的功能.(如果这令人反感,Guido 会跳入他的时间机器并更改 Python 以阻止我们这样做.)但作为一项规则,我和一般 Python 社区将我们所有的 import 语句放在模块范围内的模块顶部.

That said, I almost never use import inside a function. If importing the module creates a noticeable slowdown in your program—like it performs a long computation in its static initialization, or it's simply a massive module—and your program rarely actually needs the module for anything, it's perfectly fine to have the import only inside the functions in which it's used. (If this was distasteful, Guido would jump in his time machine and change Python to prevent us from doing it.) But as a rule, I and the general Python community put all our import statements at the top of the module in module scope.

这篇关于Python 中的本地导入语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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