IdentifiantMot de passe
Mot de passe oublié ?Je m'inscris ! (gratuit) Deferred translations 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',
# ...
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'),

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'),

# ...
for a in animals:
    print _(a)

In this case, you are marking translatable strings with the function N_(),21.5 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.


The choice of N_() here is totally arbitrary; it could have just as easily been MarkThisStringForTranslation().
See About this document... for information on suggesting changes.