wiki:Dev/i18n

Version 11 (modified by pferreir, 3 years ago) (diff)

--

Internationalization: Quick Start

From v0.98 on, Indico relies on Babel in order to manage language dictionaries and provide some basic date formatting and other locale-related functions.

Writing i18n-aware code

The basics

The basic tool in code i18n is _(). In indico, this function is available by default (no need to import''') everywhere. So, the code:

print _('Fetch the cow')

would be displayed as:

Fetchez la vache

considering that we had a Franglais dictonary loaded. A dictionary is just a map that associates an "original string" with a "translated string". Every language will have its own dictionary, that is application dependent and had to be loaded beforehand (we will see more below).

Anyone who has done (web) interface programming before can immediately see some tricky use cases that would not work. For example:

print _('Fetch %d cows' % number)

would imply that we have an infinite dictionary. Of course the fix is easy:

print _('Fetch %d cows') % number

And both Babel and msgfmt can handle format strings, and even warn you whenever the translation does not include the correct characters, etc.

Plurals

However, this is not enough. Suppose that 'number = 1'. How do we handle that? We could add an if expression and a single translation for "Fetch 1 cow". However, there is an easier/cleaner way:

from indico.util.i18n import ungettext # unicode ngettext
print ungettext("Fetch %s cow", "Fetch %s cows", number) % number

You might be asking why we do not simply do:

print "%s %s %s" % (_("Fetch"), number, ungettext("cow", "cows", number)) 

The answer is: we should never make any assumptions about the order of word in a sentence. If in English it is generally true that the verb comes before the object, for other languages that may not be right. That's why it's better to spend some more characters and translate the whole sentence - like this, translators won't see themselves limited by the assumptions you've done in your code.

Another good example:

print ungettext('Fetch the cow', 'Fetch the cows', number)

Which in Franglais would be Fetchez la vache or Fetchez les vaches (notice that the article changes!). So, do no assumptions about phrase articulaton.

Dates/Times?

It is tempting to use Python stdlib's strftime() each time we want to convert a datetime to a string. However, this function uses the currently set locale by default (process-specific), which is not thread safe. Babel provides a format_datetime function that works more or less the same way and can take a locale as parameter. We put a wrapper around it so that it takes the currently defined (thread-specific) Indico locale, making things easier for everyone.

>>> from indico.util.date_time import format_datetime, now_utc

>>> format_datetime(now_utc())
'28 Jul 2011 12:38:03'

>>> format_datetime(now_utc(), locale="fr_FR")
'28 juil. 2011 12:39:23'

>>> format_datetime(now_utc(), locale="fr_FR", format="long", timezone='Europe/Zurich')
'28 juillet 2011 12:40:05 +0000'

Timezones are also supported:

>>> from pytz import timezone
>>> format_datetime(now_utc(), locale='pt_PT', format='full', timezone=timezone('Europe/Zurich'))
'quinta-feira, 28 de Julho de 2011 14H45m18s Horário Suíça'

Custom formats may be specified using LDML:

>>> format_datetime(now_utc(), locale='es_ES', format='yyyy G')
'2011 d.C.'

More information can be found at Babel's docs on Date Formatting.

Others

http://babel.edgewall.org/wiki/Documentation/numbers.html http://babel.edgewall.org/wiki/Documentation/display.html

Common mistakes

It's very hard to write/maintain an application that is 100% internationalized, since this requires a great deal of coordination not only with the translators, but between developers as well. Not only people usually forget to properly internationalize strings, but also when they remember to do so they choose to do it at the wrong place. Here are some examples of some good/bad practices.

For example:

class UserContainer(object):
    _userTypes = {
        # wrong!
        'admin': _('Administrator'),
        'regular': _('Regular user')
    }

    # ...

    def getUserType(self):
        # can you spot the problem?
        return UserContainer._userTypes[self.user_type]

Why is this wrong? Class attributes are initialized only once, at module load time. So, since modules are normally only loaded once per process, a French user that is using this app will theoretically (see paragraph below) get the same translation as a Japanese one. The right way to do so would be delaying translation till the template is rendered: we could have a dictionary of "English" strings and then just call _() from the piece of template (or other i18n-safe code) that calls getUserType.

Fortunately our current i18n code supports (thanks to Babel) "lazy translation" (meaning that it replaces the result string with a proxy object that will only execute the translation when it is asked for its string value), and the situation above would not be problematic. However, it not at all good practice and should be avoided.

Another classic mistake is:

from persistent import Persistent

# ...

class User(Persistent):
    def __init__(self, name, position):
        self.position = _(position)

This one should be easier to spot, if you consider that Persistent objects are stored in the database. By translating position, we get it in the language that was in use at the time of object creation. The right way to do it is, once again, to translate "as late as possible".

Managing dictionaries