Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

syntax

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?

like image 896
Nick Heiner Avatar asked Jan 16 '11 22:01

Nick Heiner


People also ask

What does the STR () function do in Python?

The str() function converts values to a string form so they can be combined with other strings.

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.

What does str () return in Python?

Python str() function returns the string version of the object.

What is the use of __ str __?

The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.


1 Answers

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 _
like image 137
Mark Byers Avatar answered Sep 30 '22 14:09

Mark Byers