6.28.3.4 Deferred translations
In most coding situations, strings are translated where they are coded. Occasionally however, you need to mark strings for translation, but defer actual translation until later. A classic example is:
animals = ['mollusk', 'albatross', 'rat', 'penguin', 'python', ] # ... for a in animals: print a
Here, you want to mark the strings in the animals
list as being
translatable, but you don't actually want to translate them until they
are printed.
Here is one way you can handle this situation:
def _(message): return message animals = [_('mollusk'), _('albatross'), _('rat'), _('penguin'), _('python'), ] del _ # ... for a in animals: print _(a)
This works because the dummy definition of _() simply returns the string unchanged. And this dummy definition will temporarily override any definition of _() in the built-in namespace (until the del command). Take care, though if you have a previous definition of _ in the local namespace.
Note that the second use of _() will not identify ``a'' as being translatable to the pygettext program, since it is not a string.
Another way to handle this is with the following example:
def N_(message): return message animals = [N_('mollusk'), N_('albatross'), N_('rat'), N_('penguin'), N_('python'), ] # ... for a in animals: print _(a)
In this case, you are marking translatable strings with the function N_(),6.6 which won't conflict with any definition of _(). However, you will need to teach your message extraction program to look for translatable strings marked with N_(). pygettext and xpot both support this through the use of command line switches.
Footnotes
- The choice of N_() here is totally arbitrary; it could have just as easily been MarkThisStringForTranslation().