简体   繁体   中英

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

In the Getting things gnome code base I stumbled upon this 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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