22.1. gettext — Serviços de internacionalização multilíngues

Código Fonte: Lib/gettext.py


The gettext module provides internationalization (I18N) and localization (L10N) services for your Python modules and applications. It supports both the GNU gettext message catalog API and a higher level, class-based API that may be more appropriate for Python files. The interface described below allows you to write your module and application messages in one natural language, and provide a catalog of translated messages for running under different natural languages.

Algumas dicas sobre localização de seus módulos e aplicativos Python também são fornecidas.

22.1.1. API do GNU gettext

O módulo gettext define a API a seguir, que é muito semelhante à API do GNU gettext. Se você usar esta API, você afetará a tradução de todo o seu aplicativo globalmente. Geralmente, é isso que você deseja se o seu aplicativo for monolíngue, com a escolha do idioma dependente da localidade do seu usuário. Se você estiver localizando um módulo Python, ou se seu aplicativo precisar alternar idiomas rapidamente, provavelmente desejará usar a API baseada em classe.

gettext.bindtextdomain(domain[, localedir])

Bind the domain to the locale directory localedir. More concretely, gettext will look for binary .mo files for the given domain using the path (on Unix): localedir/language/LC_MESSAGES/domain.mo, where languages is searched for in the environment variables LANGUAGE, LC_ALL, LC_MESSAGES, and LANG respectively.

Se localedir for omitido ou None, a ligação atual para domain será retornada. 1

gettext.bind_textdomain_codeset(domain[, codeset])

Bind the domain to codeset, changing the encoding of strings returned by the gettext() family of functions. If codeset is omitted, then the current binding is returned.

Novo na versão 2.4.

gettext.textdomain([domain])

Altera ou consulta o domínio global atual. Se domain for None, o domínio global atual será retornado; caso contrário, o domínio global será definido como domain, que será retornado.

gettext.gettext(message)

Retorna a tradução localizada de message, com base no diretório global atual de domínio, idioma e localidade. Essa função geralmente é apelidada como _() no espaço de nomes local (veja exemplos abaixo).

gettext.lgettext(message)

Equivalent to gettext(), but the translation is returned in the preferred system encoding, if no other encoding was explicitly set with bind_textdomain_codeset().

Novo na versão 2.4.

gettext.dgettext(domain, message)

Like gettext(), but look the message up in the specified domain.

gettext.ldgettext(domain, message)

Equivalent to dgettext(), but the translation is returned in the preferred system encoding, if no other encoding was explicitly set with bind_textdomain_codeset().

Novo na versão 2.4.

gettext.ngettext(singular, plural, n)

Like gettext(), but consider plural forms. If a translation is found, apply the plural formula to n, and return the resulting message (some languages have more than two plural forms). If no translation is found, return singular if n is 1; return plural otherwise.

The Plural formula is taken from the catalog header. It is a C or Python expression that has a free variable n; the expression evaluates to the index of the plural in the catalog. See the GNU gettext documentation for the precise syntax to be used in .po files and the formulas for a variety of languages.

Novo na versão 2.3.

gettext.lngettext(singular, plural, n)

Equivalent to ngettext(), but the translation is returned in the preferred system encoding, if no other encoding was explicitly set with bind_textdomain_codeset().

Novo na versão 2.4.

gettext.dngettext(domain, singular, plural, n)

Semelhante a ngettext(), mas procura mensagens no domain especificado.

Novo na versão 2.3.

gettext.ldngettext(domain, singular, plural, n)

Equivalent to dngettext(), but the translation is returned in the preferred system encoding, if no other encoding was explicitly set with bind_textdomain_codeset().

Novo na versão 2.4.

Note que GNU gettext também define um método dcgettext(), mas isso não foi considerado útil e, portanto, atualmente não está implementado.

Aqui está um exemplo de uso típico para esta API:

import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print _('This is a translatable string.')

22.1.2. API baseada em classe

The class-based API of the gettext module gives you more flexibility and greater convenience than the GNU gettext API. It is the recommended way of localizing your Python applications and modules. gettext defines a “translations” class which implements the parsing of GNU .mo format files, and has methods for returning either standard 8-bit strings or Unicode strings. Instances of this “translations” class can also install themselves in the built-in namespace as the function _().

gettext.find(domain[, localedir[, languages[, all]]])

This function implements the standard .mo file search algorithm. It takes a domain, identical to what textdomain() takes. Optional localedir is as in bindtextdomain() Optional languages is a list of strings, where each string is a language code.

Se localedir não for fornecido, o diretório local do sistema padrão será usado. 2 Se languages não for fornecido, as seguintes variáveis de ambiente serão pesquisadas: LANGUAGE, LC_ALL, LC_MESSAGES e LANG. O primeiro retornando um valor não vazio é usado para a variável languages. As variáveis de ambiente devem conter uma lista de idiomas separada por dois pontos, que será dividida nos dois pontos para produzir a lista esperada de cadeias de código de idioma.

find() expande e normaliza os idiomas e itera através deles, procurando por um arquivo existente construído com esses componentes:

localedir/language/LC_MESSAGES/domain.mo

O primeiro nome de arquivo existente é retornado por find(). Se nenhum desses arquivos for encontrado, será retornado None. Se all for fornecido, ele retornará uma lista de todos os nomes de arquivos, na ordem em que aparecem na lista de idiomas ou nas variáveis de ambiente.

gettext.translation(domain[, localedir[, languages[, class_[, fallback[, codeset]]]]])

Return a Translations instance based on the domain, localedir, and languages, which are first passed to find() to get a list of the associated .mo file paths. Instances with identical .mo file names are cached. The actual class instantiated is either class_ if provided, otherwise GNUTranslations. The class’s constructor must take a single file object argument. If provided, codeset will change the charset used to encode translated strings.

Se vários arquivos forem encontrados, os arquivos posteriores serão usados como fallbacks para os anteriores. Para permitir a configuração do fallback, copy.copy() é usado para clonar cada objeto de conversão do cache; os dados reais da instância ainda são compartilhados com o cache.

If no .mo file is found, this function raises IOError if fallback is false (which is the default), and returns a NullTranslations instance if fallback is true.

Alterado na versão 2.4: Added the codeset parameter.

gettext.install(domain[, localedir[, unicode[, codeset[, names]]]])

This installs the function _() in Python’s builtins namespace, based on domain, localedir, and codeset which are passed to the function translation(). The unicode flag is passed to the resulting translation object’s install() method.

Para o parâmetro names, por favor, veja a descrição método install() do objeto de tradução.

Como visto abaixo, você normalmente marca as strings candidatas à tradução em seu aplicativo, envolvendo-as em uma chamada para a função _(), assim:

print _('This string will be translated.')

Por conveniência, você deseja que a função _() seja instalada no espaço de nomes interno do Python, para que seja facilmente acessível em todos os módulos do seu aplicativo.

Alterado na versão 2.4: Added the codeset parameter.

Alterado na versão 2.5: Added the names parameter.

22.1.2.1. A classe NullTranslations

As classes de tradução são o que realmente implementa a tradução de strings de mensagens do arquivo-fonte original para strings de mensagens traduzidas. A classe base usada por todas as classes de tradução é NullTranslations; isso fornece a interface básica que você pode usar para escrever suas próprias classes de tradução especializadas. Aqui estão os métodos de NullTranslations:

class gettext.NullTranslations([fp])

Takes an optional file object fp, which is ignored by the base class. Initializes “protected” instance variables _info and _charset which are set by derived classes, as well as _fallback, which is set through add_fallback(). It then calls self._parse(fp) if fp is not None.

_parse(fp)

No-op’d in the base class, this method takes file object fp, and reads the data from the file, initializing its message catalog. If you have an unsupported message catalog file format, you should override this method to parse your format.

add_fallback(fallback)

Adiciona fallback como o objeto reserva para o objeto de tradução atual. Um objeto de tradução deve consultar o fallback se não puder fornecer uma tradução para uma determinada mensagem.

gettext(message)

If a fallback has been set, forward gettext() to the fallback. Otherwise, return the translated message. Overridden in derived classes.

lgettext(message)

If a fallback has been set, forward lgettext() to the fallback. Otherwise, return the translated message. Overridden in derived classes.

Novo na versão 2.4.

ugettext(message)

If a fallback has been set, forward ugettext() to the fallback. Otherwise, return the translated message as a Unicode string. Overridden in derived classes.

ngettext(singular, plural, n)

If a fallback has been set, forward ngettext() to the fallback. Otherwise, return the translated message. Overridden in derived classes.

Novo na versão 2.3.

lngettext(singular, plural, n)

If a fallback has been set, forward lngettext() to the fallback. Otherwise, return the translated message. Overridden in derived classes.

Novo na versão 2.4.

ungettext(singular, plural, n)

If a fallback has been set, forward ungettext() to the fallback. Otherwise, return the translated message as a Unicode string. Overridden in derived classes.

Novo na versão 2.3.

info()

Return the “protected” _info variable.

charset()

Return the “protected” _charset variable.

output_charset()

Return the “protected” _output_charset variable, which defines the encoding used to return translated messages.

Novo na versão 2.4.

set_output_charset(charset)

Change the “protected” _output_charset variable, which defines the encoding used to return translated messages.

Novo na versão 2.4.

install([unicode[, names]])

If the unicode flag is false, this method installs self.gettext() into the built-in namespace, binding it to _. If unicode is true, it binds self.ugettext() instead. By default, unicode is false.

If the names parameter is given, it must be a sequence containing the names of functions you want to install in the builtins namespace in addition to _(). Supported names are 'gettext' (bound to self.gettext() or self.ugettext() according to the unicode flag), 'ngettext' (bound to self.ngettext() or self.ungettext() according to the unicode flag), 'lgettext' and 'lngettext'.

Observe que esta é apenas uma maneira, embora a maneira mais conveniente, de disponibilizar a função _() para o seu aplicativo. Como afeta o aplicativo inteiro globalmente, e especificamente o espaço de nomes embutido, os módulos localizados nunca devem instalar _(). Em vez disso, eles devem usar este código para disponibilizar _() para seu módulo:

import gettext
t = gettext.translation('mymodule', ...)
_ = t.gettext

Isso coloca _() apenas no espaço de nomes global do módulo e, portanto, afeta apenas as chamadas dentro deste módulo.

Alterado na versão 2.5: Added the names parameter.

22.1.2.2. A classe GNUTranslations

The gettext module provides one additional class derived from NullTranslations: GNUTranslations. This class overrides _parse() to enable reading GNU gettext format .mo files in both big-endian and little-endian format. It also coerces both message ids and message strings to Unicode.

GNUTranslations parses optional meta-data out of the translation catalog. It is convention with GNU gettext to include meta-data as the translation for the empty string. This meta-data is in RFC 822-style key: value pairs, and should contain the Project-Id-Version key. If the key Content-Type is found, then the charset property is used to initialize the “protected” _charset instance variable, defaulting to None if not found. If the charset encoding is specified, then all message ids and message strings read from the catalog are converted to Unicode using this encoding. The ugettext() method always returns a Unicode, while the gettext() returns an encoded 8-bit string. For the message id arguments of both methods, either Unicode strings or 8-bit strings containing only US-ASCII characters are acceptable. Note that the Unicode version of the methods (i.e. ugettext() and ungettext()) are the recommended interface to use for internationalized Python programs.

Todo o conjunto de pares chave/valor é colocado em um dicionário e definido como a variável de instância _info “protegida”.

If the .mo file’s magic number is invalid, or if other problems occur while reading the file, instantiating a GNUTranslations class can raise IOError.

Os seguintes métodos são substituídos a partir da implementação da classe base:

GNUTranslations.gettext(message)

Look up the message id in the catalog and return the corresponding message string, as an 8-bit string encoded with the catalog’s charset encoding, if known. If there is no entry in the catalog for the message id, and a fallback has been set, the look up is forwarded to the fallback’s gettext() method. Otherwise, the message id is returned.

GNUTranslations.lgettext(message)

Equivalent to gettext(), but the translation is returned in the preferred system encoding, if no other encoding was explicitly set with set_output_charset().

Novo na versão 2.4.

GNUTranslations.ugettext(message)

Look up the message id in the catalog and return the corresponding message string, as a Unicode string. If there is no entry in the catalog for the message id, and a fallback has been set, the look up is forwarded to the fallback’s ugettext() method. Otherwise, the message id is returned.

GNUTranslations.ngettext(singular, plural, n)

Do a plural-forms lookup of a message id. singular is used as the message id for purposes of lookup in the catalog, while n is used to determine which plural form to use. The returned message string is an 8-bit string encoded with the catalog’s charset encoding, if known.

If the message id is not found in the catalog, and a fallback is specified, the request is forwarded to the fallback’s ngettext() method. Otherwise, when n is 1 singular is returned, and plural is returned in all other cases.

Novo na versão 2.3.

GNUTranslations.lngettext(singular, plural, n)

Equivalent to gettext(), but the translation is returned in the preferred system encoding, if no other encoding was explicitly set with set_output_charset().

Novo na versão 2.4.

GNUTranslations.ungettext(singular, plural, n)

faz uma pesquisa de plural-forms de um ID de mensagem. singular é usado como o ID da mensagem para fins de pesquisa no catálogo, enquanto n é usado para determinar qual forma plural usar. A string de mensagens retornada é uma string Unicode.

If the message id is not found in the catalog, and a fallback is specified, the request is forwarded to the fallback’s ungettext() method. Otherwise, when n is 1 singular is returned, and plural is returned in all other cases.

Aqui está um exemplo:

n = len(os.listdir('.'))
cat = GNUTranslations(somefile)
message = cat.ungettext(
    'There is %(num)d file in this directory',
    'There are %(num)d files in this directory',
    n) % {'num': n}

Novo na versão 2.3.

22.1.2.3. Suporte a catálogo de mensagens do Solaris

O sistema operacional Solaris define seu próprio formato de arquivo binário .mo, mas como nenhuma documentação pode ser encontrada nesse formato, ela não é suportada no momento.

22.1.2.4. O construtor Catalog

O GNOME usa uma versão do módulo gettext de James Henstridge, mas esta versão tem uma API um pouco diferente. Seu uso documentado foi:

import gettext
cat = gettext.Catalog(domain, localedir)
_ = cat.gettext
print _('hello world')

Para compatibilidade com este módulo mais antigo, a função Catalog() é um apelido para a função translation() descrita acima.

Uma diferença entre este módulo e o de Henstridge: seus objetos de catálogo suportavam o acesso por meio de uma API de mapeamento, mas isso parece não ser utilizado e, portanto, não é atualmente suportado.

22.1.3. Internacionalizando seus programas e módulos

Internationalization (I18N), ou internacionalização (I17O) em português, refere-se à operação pela qual um programa é informado sobre vários idiomas. Localization (L10N), ou localização em português, refere-se à adaptação do seu programa, uma vez internacionalizado, aos hábitos culturais e de idioma local. Para fornecer mensagens multilíngues para seus programas Python, você precisa executar as seguintes etapas:

  1. preparar seu programa ou módulo marcando especialmente strings traduzíveis

  2. executar um conjunto de ferramentas nos arquivos marcados para gerar catálogos de mensagens não tratadas

  3. create language specific translations of the message catalogs

  4. usar o módulo gettext para que as strings das mensagens sejam traduzidas corretamente

Para preparar seu código para I18N, você precisa examinar todas as strings em seus arquivos. Qualquer string que precise ser traduzida deve ser marcada envolvendo-a em _('...') — isto é, uma chamada para a função _(). Por exemplo:

filename = 'mylog.txt'
message = _('writing a log message')
fp = open(filename, 'w')
fp.write(message)
fp.close()

Neste exemplo, a string 'writing a log message' está marcada como um candidato para tradução, enquanto as strings 'mylog.txt' e 'w' não estão.

The Python distribution comes with two tools which help you generate the message catalogs once you’ve prepared your source code. These may or may not be available from a binary distribution, but they can be found in a source distribution, in the Tools/i18n directory.

The pygettext 3 program scans all your Python source code looking for the strings you previously marked as translatable. It is similar to the GNU gettext program except that it understands all the intricacies of Python source code, but knows nothing about C or C++ source code. You don’t need GNU gettext unless you’re also going to be translating C code (such as C extension modules).

pygettext generates textual Uniforum-style human readable message catalog .pot files, essentially structured human readable files which contain every marked string in the source code, along with a placeholder for the translation strings. pygettext is a command line script that supports a similar command line interface as xgettext; for details on its use, run:

pygettext.py --help

Copies of these .pot files are then handed over to the individual human translators who write language-specific versions for every supported natural language. They send you back the filled in language-specific versions as a .po file. Using the msgfmt.py 4 program (in the Tools/i18n directory), you take the .po files from your translators and generate the machine-readable .mo binary catalog files. The .mo files are what the gettext module uses for the actual translation processing during run-time.

Como você usa o módulo gettext no seu código depende se você está internacionalizando um único módulo ou sua aplicação inteira. As próximas duas seções discutirão cada caso.

22.1.3.1. Localizando seu módulo

If you are localizing your module, you must take care not to make global changes, e.g. to the built-in namespace. You should not use the GNU gettext API but instead the class-based API.

Digamos que seu módulo seja chamado “spam” e as várias traduções do idioma natural do arquivo .mo residam em /usr/share/locale no formato GNU gettext. Aqui está o que você colocaria sobre o seu módulo:

import gettext
t = gettext.translation('spam', '/usr/share/locale')
_ = t.lgettext

If your translators were providing you with Unicode strings in their .po files, you’d instead do:

import gettext
t = gettext.translation('spam', '/usr/share/locale')
_ = t.ugettext

22.1.3.2. Localizando sua aplicação

Se você estiver localizando sua aplicação, poderá instalar a função _() globalmente no espaço de nomes embutidos, geralmente no arquivo principal do driver do sua aplicação. Isso permitirá que todos os arquivos específicos de sua aplicação usem _('...') sem precisar instalá-la explicitamente em cada arquivo.

No caso simples, você precisa adicionar apenas o seguinte código ao arquivo do driver principal da sua aplicação:

import gettext
gettext.install('myapplication')

If you need to set the locale directory or the unicode flag, you can pass these into the install() function:

import gettext
gettext.install('myapplication', '/usr/share/locale', unicode=1)

22.1.3.3. Alterando os idiomas durante o uso

Se o seu programa precisar oferecer suporte a vários idiomas ao mesmo tempo, convém criar várias instâncias de tradução e alternar entre elas explicitamente, assim:

import gettext

lang1 = gettext.translation('myapplication', languages=['en'])
lang2 = gettext.translation('myapplication', languages=['fr'])
lang3 = gettext.translation('myapplication', languages=['de'])

# start by using language1
lang1.install()

# ... time goes by, user selects language 2
lang2.install()

# ... more time goes by, user selects language 3
lang3.install()

22.1.3.4. Traduções adiadas

Na maioria das situações de codificação, as strings são traduzidas onde são codificadas. Ocasionalmente, no entanto, é necessário marcar strings para tradução, mas adiar a tradução real até mais tarde. Um exemplo clássico é:

animals = ['mollusk',
           'albatross',
           'rat',
           'penguin',
           'python', ]
# ...
for a in animals:
    print a

Aqui, você deseja marcar as strings na lista animals como traduzíveis, mas na verdade não deseja traduzi-las até que sejam impressas.

Aqui está uma maneira de lidar com esta situação:

def _(message): return message

animals = [_('mollusk'),
           _('albatross'),
           _('rat'),
           _('penguin'),
           _('python'), ]

del _

# ...
for a in animals:
    print _(a)

Isso funciona porque a definição fictícia de _() simplesmente retorna a string inalterada. E essa definição fictícia va substituir temporariamente qualquer definição de _() no espaço de nomes embutido (até o comando del). Tome cuidado, se você tiver uma definição anterior de _() no espaço de nomes local.

Note that the second use of _() will not identify “a” as being translatable to the pygettext program, since it is not a string.

Outra maneira de lidar com isso é com o seguinte exemplo:

def N_(message): return message

animals = [N_('mollusk'),
           N_('albatross'),
           N_('rat'),
           N_('penguin'),
           N_('python'), ]

# ...
for a in animals:
    print _(a)

In this case, you are marking translatable strings with the function N_(), 5 which won’t conflict with any definition of _(). However, you will need to teach your message extraction program to look for translatable strings marked with N_(). pygettext and xpot both support this through the use of command line switches.

22.1.3.5. gettext() vs. lgettext()

In Python 2.4 the lgettext() family of functions were introduced. The intention of these functions is to provide an alternative which is more compliant with the current implementation of GNU gettext. Unlike gettext(), which returns strings encoded with the same codeset used in the translation file, lgettext() will return strings encoded with the preferred system encoding, as returned by locale.getpreferredencoding(). Also notice that Python 2.4 introduces new functions to explicitly choose the codeset used in translated strings. If a codeset is explicitly set, even lgettext() will return translated strings in the requested codeset, as would be expected in the GNU gettext implementation.

22.1.4. Reconhecimentos

As seguintes pessoas contribuíram com código, feedback, sugestões de design, implementações anteriores e experiência valiosa para a criação deste módulo:

  • Peter Funk

  • James Henstridge

  • Juan David Ibáñez Palomar

  • Marc-André Lemburg

  • Martin von Löwis

  • François Pinard

  • Barry Warsaw

  • Gustavo Niemeyer

Notas de Rodapé

1

The default locale directory is system dependent; for example, on RedHat Linux it is /usr/share/locale, but on Solaris it is /usr/lib/locale. The gettext module does not try to support these system dependent defaults; instead its default is sys.prefix/share/locale. For this reason, it is always best to call bindtextdomain() with an explicit absolute path at the start of your application.

2

Consulte a nota de rodapé para a bindtextdomain() acima.

3

François Pinard has written a program called xpot which does a similar job. It is available as part of his po-utils package.

4

msgfmt.py is binary compatible with GNU msgfmt except that it provides a simpler, all-Python implementation. With this and pygettext.py, you generally won’t need to install the GNU gettext package to internationalize your Python applications.

5

The choice of N_() here is totally arbitrary; it could have just as easily been MarkThisStringForTranslation().