Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
786 views
in Technique[技术] by (71.8m points)

syntax - Python, what does an underscore before parenthesis do

Looking through some of the Django code at authentication forms I noticed the following syntax

label=_("Username")

Normally I would have just used a pair of quotes around the string. Can someone exaplain to me what the underscore and parenthesis around "Username" do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The _ is the name of a callable (function, callable object). It's usually used for the gettext function, for example in Django:

 from django.utils.translation import ugettext as _
 print _("Hello!")  # Will print Hello! if the current language is English
                    # "Bonjour !" in French
                    # ?Holà! in Spanish, etc.

As the doc says:

Python’s standard library gettext module installs _() into the global namespace, as an alias for gettext(). In Django, we have chosen not to follow this practice, for a couple of reasons:

[...]

The underscore character (_) is used to represent “the previous result” in Python’s interactive shell and doctest tests. Installing a global _() function causes interference. Explicitly importing ugettext() as _() avoids this problem.

Even if it's a convention, it may not be the case in your code. But be reassured, 99.9% of the time _ is an alias for gettext :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...