Changes

Jump to: navigation, search

Coding for translation

6 bytes removed, 10:51, 30 December 2019
m
Deferred key on lists
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:
 
<code>
animals = ['mollusk',
print(a)
</code>
 
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:
 
<code>
def _(message): return message
print(_(a))
</code>
 
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.
Another way to handle this is with the following example:
 
<code>
def _T_(message): return message
print(_(a))
</code>
 
See [https://docs.python.org/dev/library/gettext.html#deferred-translations deferred translations]

Navigation menu