开发者

Python: What does _("str") do?

开发者 https://www.devze.com 2023-02-04 08:20 出处:网络
I see this in the Django source code: description = _(\"Comma-separated integers\") description = _(\"Date (without time)\")

I see this in the Django source code:

description = _("Comma-separated integers")
description = _("Date (without time)")

What does it do? I try it in Python 3.1.3 and it fails:

>>> foo = _("bar")
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    foo = _("bar")
NameError: name '_' is not defined

No luck in 2.4.4 either:

>>> foo = _("bar")

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in -toplevel-
    foo = _("bar")
NameError: name '_' is not defined
开发者_StackOverflow

What's going on here?


The name _ is an ordinary name like any other. The syntax _(x) is calling the function called _ with the argument x. In this case it is used as an alias for ugettext, which is defined by Django. This function is used for translation of strings. From the documentation:

Specifying translation strings: In Python code

Standard translation

Specify a translation string by using the function ugettext(). It’s convention to import this as a shorter alias, _, to save typing.

To use _ in your own code you can use an import like this:

from django.utils.translation import ugettext as _


The symbol _ is just a variable name in python, and in this case it looks like it refers to a function or other "callable" which takes a string as an argument. For example

 def myfun(strng):
     return "input = " +  strng

 _ = myfun

 description = _("Comma-separated integers")


It should be noted that you cannot choose any alias to want, if you want ``makemessages```to detect the strings.

0

精彩评论

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