773 lines · 29.4 KB · TeX
RawDownload
\section{\module{gettext} ---         Multilingual internationalization services} \declaremodule{standard}{gettext}\modulesynopsis{Multilingual internationalization services.}\moduleauthor{Barry A. Warsaw}{barry@zope.com}\sectionauthor{Barry A. Warsaw}{barry@zope.com}  The \module{gettext} module provides internationalization (I18N) andlocalization (L10N) services for your Python modules and applications.It supports both the GNU \code{gettext} message catalog API and ahigher level, class-based API that may be more appropriate for Pythonfiles.  The interface described below allows you to write yourmodule and application messages in one natural language, and provide acatalog of translated messages for running under different naturallanguages. Some hints on localizing your Python modules and applications are alsogiven. \subsection{GNU \program{gettext} API} The \module{gettext} module defines the following API, which is verysimilar to the GNU \program{gettext} API.  If you use this API youwill affect the translation of your entire application globally.  Oftenthis is what you want if your application is monolingual, with the choiceof language dependent on the locale of your user.  If you arelocalizing a Python module, or if your application needs to switchlanguages on the fly, you probably want to use the class-based APIinstead. \begin{funcdesc}{bindtextdomain}{domain\optional{, localedir}}Bind the \var{domain} to the locale directory\var{localedir}.  More concretely, \module{gettext} will look forbinary \file{.mo} files for the given domain using the path (on \UNIX):\file{\var{localedir}/\var{language}/LC_MESSAGES/\var{domain}.mo},where \var{languages} is searched for in the environment variables\envvar{LANGUAGE}, \envvar{LC_ALL}, \envvar{LC_MESSAGES}, and\envvar{LANG} respectively. If \var{localedir} is omitted or \code{None}, then the current bindingfor \var{domain} is returned.\footnote{        The default locale directory is system dependent; for example,        on RedHat Linux it is \file{/usr/share/locale}, but on Solaris        it is \file{/usr/lib/locale}.  The \module{gettext} module        does not try to support these system dependent defaults;        instead its default is \file{\code{sys.prefix}/share/locale}.        For this reason, it is always best to call        \function{bindtextdomain()} with an explicit absolute path at        the start of your application.}\end{funcdesc} \begin{funcdesc}{bind_textdomain_codeset}{domain\optional{, codeset}}Bind the \var{domain} to \var{codeset}, changing the encoding ofstrings returned by the \function{gettext()} family of functions.If \var{codeset} is omitted, then the current binding is returned. \versionadded{2.4}\end{funcdesc} \begin{funcdesc}{textdomain}{\optional{domain}}Change or query the current global domain.  If \var{domain} is\code{None}, then the current global domain is returned, otherwise theglobal domain is set to \var{domain}, which is returned.\end{funcdesc} \begin{funcdesc}{gettext}{message}Return the localized translation of \var{message}, based on thecurrent global domain, language, and locale directory.  This functionis usually aliased as \function{_} in the local namespace (seeexamples below).\end{funcdesc} \begin{funcdesc}{lgettext}{message}Equivalent to \function{gettext()}, but the translation is returnedin the preferred system encoding, if no other encoding was explicitlyset with \function{bind_textdomain_codeset()}. \versionadded{2.4}\end{funcdesc} \begin{funcdesc}{dgettext}{domain, message}Like \function{gettext()}, but look the message up in the specified\var{domain}.\end{funcdesc} \begin{funcdesc}{ldgettext}{domain, message}Equivalent to \function{dgettext()}, but the translation is returnedin the preferred system encoding, if no other encoding was explicitlyset with \function{bind_textdomain_codeset()}. \versionadded{2.4}\end{funcdesc} \begin{funcdesc}{ngettext}{singular, plural, n} Like \function{gettext()}, but consider plural forms. If a translationis found, apply the plural formula to \var{n}, and return theresulting message (some languages have more than two plural forms).If no translation is found, return \var{singular} if \var{n} is 1;return \var{plural} otherwise. The Plural formula is taken from the catalog header. It is a C orPython expression that has a free variable \var{n}; the expression evaluatesto the index of the plural in the catalog. See the GNU gettextdocumentation for the precise syntax to be used in \file{.po} files and theformulas for a variety of languages. \versionadded{2.3} \end{funcdesc} \begin{funcdesc}{lngettext}{singular, plural, n}Equivalent to \function{ngettext()}, but the translation is returnedin the preferred system encoding, if no other encoding was explicitlyset with \function{bind_textdomain_codeset()}. \versionadded{2.4}\end{funcdesc} \begin{funcdesc}{dngettext}{domain, singular, plural, n}Like \function{ngettext()}, but look the message up in the specified\var{domain}. \versionadded{2.3}\end{funcdesc} \begin{funcdesc}{ldngettext}{domain, singular, plural, n}Equivalent to \function{dngettext()}, but the translation is returnedin the preferred system encoding, if no other encoding was explicitlyset with \function{bind_textdomain_codeset()}. \versionadded{2.4}\end{funcdesc}   Note that GNU \program{gettext} also defines a \function{dcgettext()}method, but this was deemed not useful and so it is currentlyunimplemented. Here's an example of typical usage for this API: \begin{verbatim}import gettextgettext.bindtextdomain('myapplication', '/path/to/my/language/directory')gettext.textdomain('myapplication')_ = gettext.gettext# ...print _('This is a translatable string.')\end{verbatim} \subsection{Class-based API} The class-based API of the \module{gettext} module gives you moreflexibility and greater convenience than the GNU \program{gettext}API.  It is the recommended way of localizing your Python applications andmodules.  \module{gettext} defines a ``translations'' class whichimplements the parsing of GNU \file{.mo} format files, and has methodsfor 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 \function{_()}. \begin{funcdesc}{find}{domain\optional{, localedir\optional{,                         languages\optional{, all}}}}This function implements the standard \file{.mo} file searchalgorithm.  It takes a \var{domain}, identical to what\function{textdomain()} takes.  Optional \var{localedir} is as in\function{bindtextdomain()}  Optional \var{languages} is a list ofstrings, where each string is a language code. If \var{localedir} is not given, then the default system localedirectory is used.\footnote{See the footnote for\function{bindtextdomain()} above.}  If \var{languages} is not given,then the following environment variables are searched: \envvar{LANGUAGE},\envvar{LC_ALL}, \envvar{LC_MESSAGES}, and \envvar{LANG}.  The first onereturning a non-empty value is used for the \var{languages} variable.The environment variables should contain a colon separated list oflanguages, which will be split on the colon to produce the expectedlist of language code strings. \function{find()} then expands and normalizes the languages, and theniterates through them, searching for an existing file built of thesecomponents: \file{\var{localedir}/\var{language}/LC_MESSAGES/\var{domain}.mo} The first such file name that exists is returned by \function{find()}.If no such file is found, then \code{None} is returned. If \var{all}is given, it returns a list of all file names, in the order in whichthey appear in the languages list or the environment variables.\end{funcdesc} \begin{funcdesc}{translation}{domain\optional{, localedir\optional{,                              languages\optional{, class_\optional{,			      fallback\optional{, codeset}}}}}}Return a \class{Translations} instance based on the \var{domain},\var{localedir}, and \var{languages}, which are first passed to\function{find()} to get a list of theassociated \file{.mo} file paths.  Instances withidentical \file{.mo} file names are cached.  The actual class instantiatedis either \var{class_} if provided, otherwise\class{GNUTranslations}.  The class's constructor must take a singlefile object argument. If provided, \var{codeset} will change thecharset used to encode translated strings. If multiple files are found, later files are used as fallbacks forearlier ones. To allow setting the fallback, \function{copy.copy}is used to clone each translation object from the cache; the actualinstance data is still shared with the cache. If no \file{.mo} file is found, this function raises\exception{IOError} if \var{fallback} is false (which is the default),and returns a \class{NullTranslations} instance if \var{fallback} istrue. \versionchanged[Added the \var{codeset} parameter]{2.4}\end{funcdesc} \begin{funcdesc}{install}{domain\optional{, localedir\optional{, unicode			  \optional{, codeset\optional{, names}}}}}This installs the function \function{_} in Python's builtin namespace,based on \var{domain}, \var{localedir}, and \var{codeset} which arepassed to the function \function{translation()}.  The \var{unicode}flag is passed to the resulting translation object's \method{install}method. For the \var{names} parameter, please see the description of thetranslation object's \method{install} method. As seen below, you usually mark the strings in your application that arecandidates for translation, by wrapping them in a call to the\function{_()} function, like this: \begin{verbatim}print _('This string will be translated.')\end{verbatim} For convenience, you want the \function{_()} function to be installed inPython's builtin namespace, so it is easily accessible in all modulesof your application.   \versionchanged[Added the \var{codeset} parameter]{2.4}\versionchanged[Added the \var{names} parameter]{2.5}\end{funcdesc} \subsubsection{The \class{NullTranslations} class}Translation classes are what actually implement the translation oforiginal source file message strings to translated message strings.The base class used by all translation classes is\class{NullTranslations}; this provides the basic interface you can useto write your own specialized translation classes.  Here are themethods of \class{NullTranslations}: \begin{methoddesc}[NullTranslations]{__init__}{\optional{fp}}Takes an optional file object \var{fp}, which is ignored by the baseclass.  Initializes ``protected'' instance variables \var{_info} and\var{_charset} which are set by derived classes, as well as \var{_fallback},which is set through \method{add_fallback}.  It then calls\code{self._parse(fp)} if \var{fp} is not \code{None}.\end{methoddesc} \begin{methoddesc}[NullTranslations]{_parse}{fp}No-op'd in the base class, this method takes file object \var{fp}, andreads the data from the file, initializing its message catalog.  Ifyou have an unsupported message catalog file format, you shouldoverride this method to parse your format.\end{methoddesc} \begin{methoddesc}[NullTranslations]{add_fallback}{fallback}Add \var{fallback} as the fallback object for the current translationobject. A translation object should consult the fallback if it cannotprovide a translation for a given message.\end{methoddesc} \begin{methoddesc}[NullTranslations]{gettext}{message}If a fallback has been set, forward \method{gettext()} to the fallback.Otherwise, return the translated message.  Overridden in derived classes.\end{methoddesc} \begin{methoddesc}[NullTranslations]{lgettext}{message}If a fallback has been set, forward \method{lgettext()} to the fallback.Otherwise, return the translated message.  Overridden in derived classes. \versionadded{2.4}\end{methoddesc} \begin{methoddesc}[NullTranslations]{ugettext}{message}If a fallback has been set, forward \method{ugettext()} to the fallback.Otherwise, return the translated message as a Unicode string.Overridden in derived classes.\end{methoddesc} \begin{methoddesc}[NullTranslations]{ngettext}{singular, plural, n}If a fallback has been set, forward \method{ngettext()} to the fallback.Otherwise, return the translated message.  Overridden in derived classes. \versionadded{2.3}\end{methoddesc} \begin{methoddesc}[NullTranslations]{lngettext}{singular, plural, n}If a fallback has been set, forward \method{ngettext()} to the fallback.Otherwise, return the translated message.  Overridden in derived classes. \versionadded{2.4}\end{methoddesc} \begin{methoddesc}[NullTranslations]{ungettext}{singular, plural, n}If a fallback has been set, forward \method{ungettext()} to the fallback.Otherwise, return the translated message as a Unicode string.Overridden in derived classes. \versionadded{2.3}\end{methoddesc} \begin{methoddesc}[NullTranslations]{info}{}Return the ``protected'' \member{_info} variable.\end{methoddesc} \begin{methoddesc}[NullTranslations]{charset}{}Return the ``protected'' \member{_charset} variable.\end{methoddesc} \begin{methoddesc}[NullTranslations]{output_charset}{}Return the ``protected'' \member{_output_charset} variable, whichdefines the encoding used to return translated messages. \versionadded{2.4}\end{methoddesc} \begin{methoddesc}[NullTranslations]{set_output_charset}{charset}Change the ``protected'' \member{_output_charset} variable, whichdefines the encoding used to return translated messages. \versionadded{2.4}\end{methoddesc} \begin{methoddesc}[NullTranslations]{install}{\optional{unicode                                              \optional{, names}}}If the \var{unicode} flag is false, this method installs\method{self.gettext()} into the built-in namespace, binding it to\samp{_}.  If \var{unicode} is true, it binds \method{self.ugettext()}instead.  By default, \var{unicode} is false. If the \var{names} parameter is given, it must be a sequence containingthe names of functions you want to install in the builtin namespace inaddition to \function{_()}. Supported names are \code{'gettext'} (boundto \method{self.gettext()} or \method{self.ugettext()} according to the\var{unicode} flag), \code{'ngettext'} (bound to \method{self.ngettext()}or \method{self.ungettext()} according to the \var{unicode} flag),\code{'lgettext'} and \code{'lngettext'}. Note that this is only one way, albeit the most convenient way, tomake the \function{_} function available to your application.  Because itaffects the entire application globally, and specifically the built-innamespace, localized modules should never install \function{_}.Instead, they should use this code to make \function{_} available totheir module: \begin{verbatim}import gettextt = gettext.translation('mymodule', ...)_ = t.gettext\end{verbatim} This puts \function{_} only in the module's global namespace and soonly affects calls within this module. \versionchanged[Added the \var{names} parameter]{2.5}\end{methoddesc} \subsubsection{The \class{GNUTranslations} class} The \module{gettext} module provides one additional class derived from\class{NullTranslations}: \class{GNUTranslations}.  This classoverrides \method{_parse()} to enable reading GNU \program{gettext}format \file{.mo} files in both big-endian and little-endian format.It also coerces both message ids and message strings to Unicode. \class{GNUTranslations} parses optional meta-data out of thetranslation catalog.  It is convention with GNU \program{gettext} toinclude meta-data as the translation for the empty string.  Thismeta-data is in \rfc{822}-style \code{key: value} pairs, and shouldcontain the \code{Project-Id-Version} key.  If the key\code{Content-Type} is found, then the \code{charset} property is usedto initialize the ``protected'' \member{_charset} instance variable,defaulting to \code{None} if not found.  If the charset encoding isspecified, then all message ids and message strings read from thecatalog are converted to Unicode using this encoding.  The\method{ugettext()} method always returns a Unicode, while the\method{gettext()} returns an encoded 8-bit string.  For the messageid arguments of both methods, either Unicode strings or 8-bit stringscontaining only US-ASCII characters are acceptable.  Note that theUnicode version of the methods (i.e. \method{ugettext()} and\method{ungettext()}) are the recommended interface to use forinternationalized Python programs. The entire set of key/value pairs are placed into a dictionary and setas the ``protected'' \member{_info} instance variable. If the \file{.mo} file's magic number is invalid, or if other problemsoccur while reading the file, instantiating a \class{GNUTranslations} classcan raise \exception{IOError}. The following methods are overridden from the base class implementation: \begin{methoddesc}[GNUTranslations]{gettext}{message}Look up the \var{message} id in the catalog and return thecorresponding message string, as an 8-bit string encoded with thecatalog's charset encoding, if known.  If there is no entry in thecatalog for the \var{message} id, and a fallback has been set, thelook up is forwarded to the fallback's \method{gettext()} method.Otherwise, the \var{message} id is returned.\end{methoddesc} \begin{methoddesc}[GNUTranslations]{lgettext}{message}Equivalent to \method{gettext()}, but the translation is returnedin the preferred system encoding, if no other encoding was explicitlyset with \method{set_output_charset()}. \versionadded{2.4}\end{methoddesc} \begin{methoddesc}[GNUTranslations]{ugettext}{message}Look up the \var{message} id in the catalog and return thecorresponding message string, as a Unicode string.  If there is noentry in the catalog for the \var{message} id, and a fallback has beenset, the look up is forwarded to the fallback's \method{ugettext()}method.  Otherwise, the \var{message} id is returned.\end{methoddesc} \begin{methoddesc}[GNUTranslations]{ngettext}{singular, plural, n}Do a plural-forms lookup of a message id.  \var{singular} is used asthe message id for purposes of lookup in the catalog, while \var{n} isused to determine which plural form to use.  The returned messagestring 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 isspecified, the request is forwarded to the fallback's\method{ngettext()} method.  Otherwise, when \var{n} is 1 \var{singular} isreturned, and \var{plural} is returned in all other cases. \versionadded{2.3}\end{methoddesc} \begin{methoddesc}[GNUTranslations]{lngettext}{singular, plural, n}Equivalent to \method{gettext()}, but the translation is returnedin the preferred system encoding, if no other encoding was explicitlyset with \method{set_output_charset()}. \versionadded{2.4}\end{methoddesc} \begin{methoddesc}[GNUTranslations]{ungettext}{singular, plural, n}Do a plural-forms lookup of a message id.  \var{singular} is used asthe message id for purposes of lookup in the catalog, while \var{n} isused to determine which plural form to use.  The returned messagestring is a Unicode string. If the message id is not found in the catalog, and a fallback isspecified, the request is forwarded to the fallback's\method{ungettext()} method.  Otherwise, when \var{n} is 1 \var{singular} isreturned, and \var{plural} is returned in all other cases. Here is an example: \begin{verbatim}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}\end{verbatim} \versionadded{2.3}\end{methoddesc} \subsubsection{Solaris message catalog support} The Solaris operating system defines its own binary\file{.mo} file format, but since no documentation can be found onthis format, it is not supported at this time. \subsubsection{The Catalog constructor} GNOME\index{GNOME} uses a version of the \module{gettext} module byJames Henstridge, but this version has a slightly different API.  Itsdocumented usage was: \begin{verbatim}import gettextcat = gettext.Catalog(domain, localedir)_ = cat.gettextprint _('hello world')\end{verbatim} For compatibility with this older module, the function

Lines 1–500 of 773.