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

In the gnome source code base, I came across this import statement

from GTG import _ 

and I have no idea what that means, I have never seen this in the documentation, and the quick / google search did not change anything.

+7
python import
source share
2 answers

from GTG import _ imports the _ function from the GTG module into the "current" namespace.

Typically, the _ function is an alias for gettext.gettext() , a function that displays a localized version of a given message. The documentation gives an idea of ​​what usually happens somewhere else in a module far, far:

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

This imports the function / class / module _ into the current namespace. So instead of typing GTG._ , you just need to type _ to use it.

Here are some documents:

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

It should be noted that you should use this with caution. Doing this too much can pollute the current namespace, make the code more difficult to read, and possibly introduce runtime errors. Also, NEVER NEVER do this:

 from MODULE import * 

as it is heavily polluting the current namespace.

This method is most useful when you know that you are only going to use one or two functions / classes / modules from a module, since it only imports the listed assets.

For example, if I want to use the imap function from the itertools module, and I know that I will not need other itertools functions, I could write

 from itertools import imap 

and it will only import the imap function.

As I said earlier, this should be used with caution, as some people might think that

 import itertools # ... more code ... new_list = itertools.imap(my_func, my_list) 

more readable than

 from itertools import imap # ... more code ... new_list = imap(my_func, my_list) 

since it accurately determines which module the imap function came from.

+4
source share

All Articles