开发者

what does "from MODULE import _" do in python?

开发者 https://www.devze.com 2022-12-31 20:04 出处:网络
In the Getting things gnome code base I stumbled upon th开发者_如何学Cis import statement from GTG import _

In the Getting things gnome code base I stumbled upon th开发者_如何学Cis import statement

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.

Usually, the _ function is an alias for gettext.gettext(), a function that shows the localized version of a given message. 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. So instead of having to type GTG._, you just have to type _ to use it.

Here is some documentation:

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

from itertools import imap

and it would only import the imap function.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消