Nick Heiner
Nick Heiner

Reputation: 122530

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

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

What's going on here?

Upvotes: 9

Views: 5033

Answers (3)

Izz ad-Din Ruhulessin
Izz ad-Din Ruhulessin

Reputation: 6175

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

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838716

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 _

Upvotes: 19

Andrew Jaffe
Andrew Jaffe

Reputation: 27097

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")

Upvotes: 1

Related Questions