From Fedora Project Wiki

Revision as of 16:36, 24 May 2008 by Ravidiip (talk | contribs) (1 revision(s))

Collection of Tips for Programming in Python

This page is not a final page. It is a collection of ideas that need to be vetted and then merged into other documents.

i18n

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 fallback=True. Without that, python will traceback when a locale is used where there is no locale information present.

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}

translatable_string = _('%s is a %s %s') % (name, adjective, noun)

translatable_string = name + _(' is a ') + adjective + ' ' + noun

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.