I've seen a few examples defining choice fields like so:
COUNTRIES = ( ('fr', _('France')), ('de', _('Germany')), ... )
(Source: http://code.djangoproject.com/ticket/5446 Also see: http://djangosnippets.org/snippets/494/)
What is the meaning of the leading underscores? And why is the second value in the tuple even parenthesized?
A single leading underscore in front of a variable, a function, or a method name means that these objects are used internally. This is more of a syntax hint to the programmer and is not enforced by the Python interpreter which means that these objects can still be accessed in one way on another from another script.
The use of double underscore ( __ ) in front of a name (specifically a method name) is not a convention; it has a specific meaning to the interpreter. Python mangles these names and it is used to avoid name clashes with names defined by subclasses.
Python automatically stores the value of the last expression in the interpreter to a particular variable called "_." You can also assign these value to another variable if you want. You can use it as a normal variable.
Single standalone underscore _ is a valid character for a Python identifier, so it can be used as a variable name. According to Python doc, the special identifier _ is used in the interactive interpreter to store the result of the last evaluation. It is stored in the builtin module.
The leading underscore is the commonly used function alias for the one of the ugettext functions used by the internationalization (i18n) mechanics.
It means that when you have i18n running, the choicefield labels will be translated into the appropriate end-user language, if a translation is available.
At the top of a file that features this kind of syntax, you should see (or if not, you should have) something like:
from django.utils.translation import ugettext_lazy as _
See the docs here for more details
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