User:Toshio/Python I18N

From FedoraProject

< User:Toshio(Difference between revisions)
Jump to: navigation, search
m (moved ToshioKuratomi/PythonDevelopersGuide to User:Toshio/Python I18N: Take ownership of this and enhance it)
(Add draft notice with note about kitchen)
Line 1: Line 1:
= Collection of Tips for Programming in Python =
+
{{draft|Freshly copied over from the old wikiI need to add how to use the kitchen library to setup i18n to this}}
 
+
This page is not a final pageIt is a collection of ideas that need to be vetted and then merged into other documents.
+
 
+
== i18n ==
+
 
+
 
=== Setup ===
 
=== Setup ===
  

Revision as of 13:29, 29 July 2010

Warning (medium size).png
This page is a draft only
It is still under construction and content may change. Do not rely on the information on this page. Freshly copied over from the old wiki. I need to add how to use the kitchen library to setup i18n to this

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.