User:Toshio/Python I18N

Setting up and using gettext for i18n can be daunting, not because the code is hard, but because few people have documented how to do it.

Setup
For an application you can use python's gettext.install to make "_" available as a builtin (and thus available everywhere.) See the python library documentation for doing that. For a module, you don't want to pollute the namespace that way. Instead, in every module, you need to do the following::

import gettext translation = gettext.translation('python-fedora', '/usr/share/locale', fallback=True) _ = translation.ugettext

This is a slight variation on what is written in the python library documentation. Notably, we add. Without that, python will traceback when a locale is used where there is no locale information present.

The kitchen.i18n module provides a few handy methods for setting this up. If your code is pretty simple, have a look at easy_gettext_setup. If you have more complex needs, look at get_translation_object

Formatting strings
It is important when formatting strings that will be localized to use a dictionary for substitution::

noun = _('rhinoceros') adjective = _('cranky') name = 'Jamie'

translatable_string = _('%(name)s is a %(adjective)s %(noun)s') % {'name': name, 'adjective': adjective, 'noun': noun}
 * 1) Correct!

translatable_string = _('%s is a %s %s') % (name, adjective, noun) translatable_string = name + _(' is a ') + adjective + ' ' + noun
 * 1) Incorrect!

This is because the translation of the string might need to reorder the words. The dictionary approach to formatting the string allows this but the other two approaches do not.