简体   繁体   English

什么“来自MODULE import _”在python中做什么?

[英]what does “from MODULE import _” do in python?

In the Getting things gnome code base I stumbled upon this import statement 在Getting things gnome代码库中,我偶然发现了这个import语句

from GTG import _  

and have no idea what it means, never seen this in the documentation and a quick so / google search didn't turn anything up. 并且不知道它意味着什么,从未在文档中看到这一点,并且快速的搜索/谷歌搜索没有改变任何东西。

from GTG import _ imports the _ function from the GTG module into the "current" namespace. from GTG import __函数从GTG模块导入“当前”命名空间。

Usually, the _ function is an alias for gettext.gettext() , a function that shows the localized version of a given message. 通常, _ function是gettext.gettext()的别名, gettext.gettext()是一个显示给定消息的本地化版本的函数。 The documentation gives a picture of what is usually going on somewhere else in a module far, far away: 该文档给出了远在远处的模块中其他地方通常会发生什么的图片:

import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print _('This is a translatable string.')

This imports the function/class/module _ into the current namespace. 这会将函数/ class / module _导入当前名称空间。 So instead of having to type GTG._ , you just have to type _ to use it. 因此,您只需键入_即可使用它,而无需键入GTG._

Here is some documentation: 这是一些文档:

http://docs.python.org/tutorial/modules.html#more-on-modules http://docs.python.org/tutorial/modules.html#more-on-modules

It should be noted that you should use this with care. 应该注意的是,你应该小心使用它。 Doing this too much could pollute the current namespace, making code harder to read, and possibly introducing runtime errors. 执行此操作可能会污染当前命名空间,使代码更难以阅读,并可能引入运行时错误。 Also, NEVER NEVER NEVER do this: 此外,永远不要这样做:

from MODULE import *

, as it very much pollutes the current namespace. ,因为它非常污染当前的命名空间。

This technique is most useful when you know you are only going to use one or two functions/classes/modules from a module, since doing this only imports the listed assets. 当您知道只使用模块中的一个或两个函数/类/模块时,此技术非常有用,因为这样做只会导入列出的资产。

For example, if I want to use the imap function from the itertools module, and I know I won't need any other itertools functions, I could write 例如,如果我想使用itertools模块中的imap函数,我知道我不需要任何其他的itertools函数,我可以写

from itertools import imap

and it would only import the imap function. 它只会导入imap函数。

Like I said earlier, this should be used with care, since some people may think that 就像我之前说的那样,这应该谨慎使用,因为有些人可能会这么认为

import itertools

# ... more code ...

new_list = itertools.imap(my_func, my_list)

is more readable than 比...更具可读性

from itertools import imap

# ... more code ...

new_list = imap(my_func, my_list)

as it makes it clear exactly which module the imap function came from. 因为它清楚地表明了imap函数来自哪个模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM