2
def host(self):
    """ Return user host """
    _ = self._request.getText
    host = self.isCurrentUser() and self._cfg.show_hosts and self._request.remote_addr
    return host or _("<unknown>")

for this code , _ is represent the getText function of _request . and i found _ sometimes represent for the last output of the command .

but i wonder why not use self._request.getText("") directly. and if i replace the _ with another variable,it still work . is there any difference ?

thanks for answer me .

mike
  • 1,127
  • 4
  • 17
  • 34
  • The former question is also a duplicate of the latter, which predates either of these by over a year – Air Feb 07 '14 at 17:45

2 Answers2

4

It's mostly a matter of convention. When your application is subject to i18n (internationalization), almost all your (display) strings go through a function to turn them into the proper language. Having a long function name for that will make the code unreadable, so naming it _ has become sort of a convention. (Also, some of the tools that help with i18n can look at your source code, recognize _("key") and make a list of keys that you need to translate.

Ulrich Schwarz
  • 7,598
  • 1
  • 36
  • 48
  • 9
    Also in non i18n-related contexts, the `_` variable is often used as a throw-away variable, it means that its value is of no importance for the programmer and will be discarded. Example: `for _ in range(0, 10):`. – Andrea Spadaccini Feb 15 '11 at 07:47
2

_ is used in Python both as a throw-value variable, which are sometimes useful when you are using python interpreter as a calculator and you want the result of the last expression.

>>> 22.0/7
3.1428571428571428
>>> _ * 42

But using _ for a throw away variable is not really a good practice. It tends to confuse people a lot. Instead use a temp variable name.

There seems to be practice of assigning _ to a Factory class which produces i18n message. It is more of a convention and practice than anything of significant.

Following SO question is almost the same as yours.

Community
  • 1
  • 1
Senthil Kumaran
  • 54,681
  • 14
  • 94
  • 131