开发者

the underscore of python [duplicate]

This question already has answers here: Underscore _ as variable name in Python [duplicate] (3 answers) Closed 9 years ago.
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 .

b开发者_开发知识库ut 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 .


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.


_ 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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜