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?
The str() function converts values to a string form so they can be combined with other strings.
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.
Python str() function returns the string version of the object.
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.
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 _
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With