blob: 593d964c8d1ba8e2773651f737d90d767db151a5 [file] [log] [blame]
Barry Warsaw0691a6b2000-08-30 03:27:10 +00001\section{\module{gettext} ---
2 Multilingual internationalization services}
3
4\declaremodule{standard}{gettext}
5\modulesynopsis{Multilingual internationalization services.}
Andrew M. Kuchlingc62af022004-01-08 15:01:08 +00006\moduleauthor{Barry A. Warsaw}{barry@zope.com}
7\sectionauthor{Barry A. Warsaw}{barry@zope.com}
Barry Warsaw0691a6b2000-08-30 03:27:10 +00008
9
10The \module{gettext} module provides internationalization (I18N) and
11localization (L10N) services for your Python modules and applications.
Fred Draked576e9d2000-08-30 04:19:20 +000012It supports both the GNU \code{gettext} message catalog API and a
Barry Warsaw0691a6b2000-08-30 03:27:10 +000013higher level, class-based API that may be more appropriate for Python
14files. The interface described below allows you to write your
15module and application messages in one natural language, and provide a
16catalog of translated messages for running under different natural
17languages.
18
19Some hints on localizing your Python modules and applications are also
20given.
21
22\subsection{GNU \program{gettext} API}
23
24The \module{gettext} module defines the following API, which is very
25similar to the GNU \program{gettext} API. If you use this API you
26will affect the translation of your entire application globally. Often
27this is what you want if your application is monolingual, with the choice
28of language dependent on the locale of your user. If you are
29localizing a Python module, or if your application needs to switch
30languages on the fly, you probably want to use the class-based API
31instead.
32
Fred Draked576e9d2000-08-30 04:19:20 +000033\begin{funcdesc}{bindtextdomain}{domain\optional{, localedir}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +000034Bind the \var{domain} to the locale directory
35\var{localedir}. More concretely, \module{gettext} will look for
Fred Draked576e9d2000-08-30 04:19:20 +000036binary \file{.mo} files for the given domain using the path (on \UNIX):
Barry Warsaw0691a6b2000-08-30 03:27:10 +000037\file{\var{localedir}/\var{language}/LC_MESSAGES/\var{domain}.mo},
38where \var{languages} is searched for in the environment variables
Fred Draked576e9d2000-08-30 04:19:20 +000039\envvar{LANGUAGE}, \envvar{LC_ALL}, \envvar{LC_MESSAGES}, and
40\envvar{LANG} respectively.
Barry Warsaw0691a6b2000-08-30 03:27:10 +000041
Fred Draked576e9d2000-08-30 04:19:20 +000042If \var{localedir} is omitted or \code{None}, then the current binding
43for \var{domain} is returned.\footnote{
Fred Drake91f2f262001-07-06 19:28:48 +000044 The default locale directory is system dependent; for example,
45 on RedHat Linux it is \file{/usr/share/locale}, but on Solaris
46 it is \file{/usr/lib/locale}. The \module{gettext} module
47 does not try to support these system dependent defaults;
48 instead its default is \file{\code{sys.prefix}/share/locale}.
49 For this reason, it is always best to call
Fred Draked576e9d2000-08-30 04:19:20 +000050 \function{bindtextdomain()} with an explicit absolute path at
51 the start of your application.}
Barry Warsaw0691a6b2000-08-30 03:27:10 +000052\end{funcdesc}
53
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +000054\begin{funcdesc}{bind_textdomain_codeset}{domain\optional{, codeset}}
55Bind the \var{domain} to \var{codeset}, changing the encoding of
56strings returned by the \function{gettext()} family of functions.
57If \var{codeset} is omitted, then the current binding is returned.
58
59\versionadded{2.4}
60\end{funcdesc}
61
Fred Draked576e9d2000-08-30 04:19:20 +000062\begin{funcdesc}{textdomain}{\optional{domain}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +000063Change or query the current global domain. If \var{domain} is
64\code{None}, then the current global domain is returned, otherwise the
65global domain is set to \var{domain}, which is returned.
66\end{funcdesc}
67
68\begin{funcdesc}{gettext}{message}
69Return the localized translation of \var{message}, based on the
70current global domain, language, and locale directory. This function
71is usually aliased as \function{_} in the local namespace (see
72examples below).
73\end{funcdesc}
74
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +000075\begin{funcdesc}{lgettext}{message}
76Equivalent to \function{gettext()}, but the translation is returned
77in the preferred system encoding, if no other encoding was explicitly
78set with \function{bind_textdomain_codeset()}.
79
80\versionadded{2.4}
81\end{funcdesc}
82
Barry Warsaw0691a6b2000-08-30 03:27:10 +000083\begin{funcdesc}{dgettext}{domain, message}
84Like \function{gettext()}, but look the message up in the specified
85\var{domain}.
86\end{funcdesc}
87
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +000088\begin{funcdesc}{ldgettext}{domain, message}
89Equivalent to \function{dgettext()}, but the translation is returned
90in the preferred system encoding, if no other encoding was explicitly
91set with \function{bind_textdomain_codeset()}.
92
93\versionadded{2.4}
94\end{funcdesc}
95
Martin v. Löwisd8996052002-11-21 21:45:32 +000096\begin{funcdesc}{ngettext}{singular, plural, n}
97
98Like \function{gettext()}, but consider plural forms. If a translation
99is found, apply the plural formula to \var{n}, and return the
100resulting message (some languages have more than two plural forms).
101If no translation is found, return \var{singular} if \var{n} is 1;
102return \var{plural} otherwise.
103
104The Plural formula is taken from the catalog header. It is a C or
105Python expression that has a free variable n; the expression evaluates
106to the index of the plural in the catalog. See the GNU gettext
107documentation for the precise syntax to be used in .po files, and the
108formulas for a variety of languages.
109
110\versionadded{2.3}
111
112\end{funcdesc}
113
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000114\begin{funcdesc}{lngettext}{singular, plural, n}
115Equivalent to \function{ngettext()}, but the translation is returned
116in the preferred system encoding, if no other encoding was explicitly
117set with \function{bind_textdomain_codeset()}.
118
119\versionadded{2.4}
120\end{funcdesc}
121
Martin v. Löwisd8996052002-11-21 21:45:32 +0000122\begin{funcdesc}{dngettext}{domain, singular, plural, n}
123Like \function{ngettext()}, but look the message up in the specified
124\var{domain}.
125
126\versionadded{2.3}
127\end{funcdesc}
128
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000129\begin{funcdesc}{ldngettext}{domain, singular, plural, n}
130Equivalent to \function{dngettext()}, but the translation is returned
131in the preferred system encoding, if no other encoding was explicitly
132set with \function{bind_textdomain_codeset()}.
133
134\versionadded{2.4}
135\end{funcdesc}
136
137
Martin v. Löwisd8996052002-11-21 21:45:32 +0000138
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000139Note that GNU \program{gettext} also defines a \function{dcgettext()}
140method, but this was deemed not useful and so it is currently
141unimplemented.
142
143Here's an example of typical usage for this API:
144
145\begin{verbatim}
146import gettext
147gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
148gettext.textdomain('myapplication')
149_ = gettext.gettext
150# ...
151print _('This is a translatable string.')
152\end{verbatim}
153
154\subsection{Class-based API}
155
156The class-based API of the \module{gettext} module gives you more
157flexibility and greater convenience than the GNU \program{gettext}
158API. It is the recommended way of localizing your Python applications and
159modules. \module{gettext} defines a ``translations'' class which
160implements the parsing of GNU \file{.mo} format files, and has methods
161for returning either standard 8-bit strings or Unicode strings.
Andrew M. Kuchling099bd522004-07-10 16:01:10 +0000162Instances of this ``translations'' class can also install themselves
163in the built-in namespace as the function \function{_()}.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000164
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000165\begin{funcdesc}{find}{domain\optional{, localedir\optional{,
166 languages\optional{, all}}}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000167This function implements the standard \file{.mo} file search
168algorithm. It takes a \var{domain}, identical to what
Barry Warsaw91b81c42001-10-18 19:41:48 +0000169\function{textdomain()} takes. Optional \var{localedir} is as in
170\function{bindtextdomain()} Optional \var{languages} is a list of
171strings, where each string is a language code.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000172
173If \var{localedir} is not given, then the default system locale
Fred Draked576e9d2000-08-30 04:19:20 +0000174directory is used.\footnote{See the footnote for
175\function{bindtextdomain()} above.} If \var{languages} is not given,
176then the following environment variables are searched: \envvar{LANGUAGE},
177\envvar{LC_ALL}, \envvar{LC_MESSAGES}, and \envvar{LANG}. The first one
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000178returning a non-empty value is used for the \var{languages} variable.
Barry Warsaw91b81c42001-10-18 19:41:48 +0000179The environment variables should contain a colon separated list of
180languages, which will be split on the colon to produce the expected
181list of language code strings.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000182
183\function{find()} then expands and normalizes the languages, and then
184iterates through them, searching for an existing file built of these
185components:
186
187\file{\var{localedir}/\var{language}/LC_MESSAGES/\var{domain}.mo}
188
189The first such file name that exists is returned by \function{find()}.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000190If no such file is found, then \code{None} is returned. If \var{all}
191is given, it returns a list of all file names, in the order in which
192they appear in the languages list or the environment variables.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000193\end{funcdesc}
194
Fred Draked576e9d2000-08-30 04:19:20 +0000195\begin{funcdesc}{translation}{domain\optional{, localedir\optional{,
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000196 languages\optional{, class_\optional{,
197 fallback\optional{, codeset}}}}}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000198Return a \class{Translations} instance based on the \var{domain},
199\var{localedir}, and \var{languages}, which are first passed to
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000200\function{find()} to get a list of the
201associated \file{.mo} file paths. Instances with
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000202identical \file{.mo} file names are cached. The actual class instantiated
203is either \var{class_} if provided, otherwise
204\class{GNUTranslations}. The class's constructor must take a single
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000205file object argument. If provided, \var{codeset} will change the
206charset used to encode translated strings.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000207
208If multiple files are found, later files are used as fallbacks for
209earlier ones. To allow setting the fallback, \function{copy.copy}
210is used to clone each translation object from the cache; the actual
211instance data is still shared with the cache.
212
213If no \file{.mo} file is found, this function raises
214\exception{IOError} if \var{fallback} is false (which is the default),
215and returns a \class{NullTranslations} instance if \var{fallback} is
216true.
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000217
218\versionchanged[Added the \var{codeset} parameter]{2.4}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000219\end{funcdesc}
220
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000221\begin{funcdesc}{install}{domain\optional{, localedir\optional{, unicode
222 \optional{, codeset}}}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000223This installs the function \function{_} in Python's builtin namespace,
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000224based on \var{domain}, \var{localedir}, and \var{codeset} which are
225passed to the function \function{translation()}. The \var{unicode}
226flag is passed to the resulting translation object's \method{install}
227method.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000228
229As seen below, you usually mark the strings in your application that are
Fred Drake91f2f262001-07-06 19:28:48 +0000230candidates for translation, by wrapping them in a call to the
231\function{_()} function, like this:
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000232
233\begin{verbatim}
234print _('This string will be translated.')
235\end{verbatim}
236
237For convenience, you want the \function{_()} function to be installed in
238Python's builtin namespace, so it is easily accessible in all modules
239of your application.
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000240
241\versionchanged[Added the \var{codeset} parameter]{2.4}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000242\end{funcdesc}
243
244\subsubsection{The \class{NullTranslations} class}
245Translation classes are what actually implement the translation of
246original source file message strings to translated message strings.
247The base class used by all translation classes is
248\class{NullTranslations}; this provides the basic interface you can use
249to write your own specialized translation classes. Here are the
250methods of \class{NullTranslations}:
251
Fred Draked576e9d2000-08-30 04:19:20 +0000252\begin{methoddesc}[NullTranslations]{__init__}{\optional{fp}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000253Takes an optional file object \var{fp}, which is ignored by the base
254class. Initializes ``protected'' instance variables \var{_info} and
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000255\var{_charset} which are set by derived classes, as well as \var{_fallback},
256which is set through \method{add_fallback}. It then calls
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000257\code{self._parse(fp)} if \var{fp} is not \code{None}.
258\end{methoddesc}
259
260\begin{methoddesc}[NullTranslations]{_parse}{fp}
261No-op'd in the base class, this method takes file object \var{fp}, and
262reads the data from the file, initializing its message catalog. If
263you have an unsupported message catalog file format, you should
264override this method to parse your format.
265\end{methoddesc}
266
Martin v. Löwiscebcc612003-08-05 05:54:15 +0000267\begin{methoddesc}[NullTranslations]{add_fallback}{fallback}
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000268Add \var{fallback} as the fallback object for the current translation
269object. A translation object should consult the fallback if it cannot
270provide a translation for a given message.
271\end{methoddesc}
272
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000273\begin{methoddesc}[NullTranslations]{gettext}{message}
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000274If a fallback has been set, forward \method{gettext()} to the fallback.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000275Otherwise, return the translated message. Overridden in derived classes.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000276\end{methoddesc}
277
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000278\begin{methoddesc}[NullTranslations]{lgettext}{message}
279If a fallback has been set, forward \method{lgettext()} to the fallback.
280Otherwise, return the translated message. Overridden in derived classes.
281
282\versionadded{2.4}
283\end{methoddesc}
284
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000285\begin{methoddesc}[NullTranslations]{ugettext}{message}
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000286If a fallback has been set, forward \method{ugettext()} to the fallback.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000287Otherwise, return the translated message as a Unicode string.
288Overridden in derived classes.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000289\end{methoddesc}
290
Martin v. Löwisd8996052002-11-21 21:45:32 +0000291\begin{methoddesc}[NullTranslations]{ngettext}{singular, plural, n}
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000292If a fallback has been set, forward \method{ngettext()} to the fallback.
Martin v. Löwisd8996052002-11-21 21:45:32 +0000293Otherwise, return the translated message. Overridden in derived classes.
294
295\versionadded{2.3}
296\end{methoddesc}
297
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000298\begin{methoddesc}[NullTranslations]{lngettext}{singular, plural, n}
299If a fallback has been set, forward \method{ngettext()} to the fallback.
300Otherwise, return the translated message. Overridden in derived classes.
301
302\versionadded{2.4}
303\end{methoddesc}
304
Martin v. Löwisd8996052002-11-21 21:45:32 +0000305\begin{methoddesc}[NullTranslations]{ungettext}{singular, plural, n}
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000306If a fallback has been set, forward \method{ungettext()} to the fallback.
Martin v. Löwisd8996052002-11-21 21:45:32 +0000307Otherwise, return the translated message as a Unicode string.
308Overridden in derived classes.
309
310\versionadded{2.3}
311\end{methoddesc}
312
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000313\begin{methoddesc}[NullTranslations]{info}{}
Fred Draked576e9d2000-08-30 04:19:20 +0000314Return the ``protected'' \member{_info} variable.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000315\end{methoddesc}
316
317\begin{methoddesc}[NullTranslations]{charset}{}
Fred Draked576e9d2000-08-30 04:19:20 +0000318Return the ``protected'' \member{_charset} variable.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000319\end{methoddesc}
320
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000321\begin{methoddesc}[NullTranslations]{output_charset}{}
322Return the ``protected'' \member{_output_charset} variable, which
323defines the encoding used to return translated messages.
324
325\versionadded{2.4}
326\end{methoddesc}
327
328\begin{methoddesc}[NullTranslations]{set_output_charset}{charset}
329Change the ``protected'' \member{_output_charset} variable, which
330defines the encoding used to return translated messages.
331
332\versionadded{2.4}
333\end{methoddesc}
334
Fred Draked576e9d2000-08-30 04:19:20 +0000335\begin{methoddesc}[NullTranslations]{install}{\optional{unicode}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000336If the \var{unicode} flag is false, this method installs
Fred Draked576e9d2000-08-30 04:19:20 +0000337\method{self.gettext()} into the built-in namespace, binding it to
338\samp{_}. If \var{unicode} is true, it binds \method{self.ugettext()}
339instead. By default, \var{unicode} is false.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000340
341Note that this is only one way, albeit the most convenient way, to
342make the \function{_} function available to your application. Because it
343affects the entire application globally, and specifically the built-in
344namespace, localized modules should never install \function{_}.
345Instead, they should use this code to make \function{_} available to
346their module:
347
348\begin{verbatim}
349import gettext
350t = gettext.translation('mymodule', ...)
351_ = t.gettext
352\end{verbatim}
353
354This puts \function{_} only in the module's global namespace and so
355only affects calls within this module.
356\end{methoddesc}
357
358\subsubsection{The \class{GNUTranslations} class}
359
360The \module{gettext} module provides one additional class derived from
361\class{NullTranslations}: \class{GNUTranslations}. This class
362overrides \method{_parse()} to enable reading GNU \program{gettext}
363format \file{.mo} files in both big-endian and little-endian format.
Barry Warsaw50889232003-04-24 18:14:49 +0000364It also coerces both message ids and message strings to Unicode.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000365
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000366\class{GNUTranslations} parses optional meta-data out of the
367translation catalog. It is convention with GNU \program{gettext} to
368include meta-data as the translation for the empty string. This
Barry Warsaw50889232003-04-24 18:14:49 +0000369meta-data is in \rfc{822}-style \code{key: value} pairs, and should
370contain the \code{Project-Id-Version} key. If the key
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000371\code{Content-Type} is found, then the \code{charset} property is used
372to initialize the ``protected'' \member{_charset} instance variable,
Barry Warsaw50889232003-04-24 18:14:49 +0000373defaulting to \code{None} if not found. If the charset encoding is
374specified, then all message ids and message strings read from the
375catalog are converted to Unicode using this encoding. The
376\method{ugettext()} method always returns a Unicode, while the
377\method{gettext()} returns an encoded 8-bit string. For the message
378id arguments of both methods, either Unicode strings or 8-bit strings
379containing only US-ASCII characters are acceptable. Note that the
380Unicode version of the methods (i.e. \method{ugettext()} and
381\method{ungettext()}) are the recommended interface to use for
382internationalized Python programs.
383
384The entire set of key/value pairs are placed into a dictionary and set
385as the ``protected'' \member{_info} instance variable.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000386
387If the \file{.mo} file's magic number is invalid, or if other problems
388occur while reading the file, instantiating a \class{GNUTranslations} class
389can raise \exception{IOError}.
390
Barry Warsaw50889232003-04-24 18:14:49 +0000391The following methods are overridden from the base class implementation:
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000392
Barry Warsaw50889232003-04-24 18:14:49 +0000393\begin{methoddesc}[GNUTranslations]{gettext}{message}
394Look up the \var{message} id in the catalog and return the
395corresponding message string, as an 8-bit string encoded with the
396catalog's charset encoding, if known. If there is no entry in the
397catalog for the \var{message} id, and a fallback has been set, the
398look up is forwarded to the fallback's \method{gettext()} method.
399Otherwise, the \var{message} id is returned.
400\end{methoddesc}
Martin v. Löwisd8996052002-11-21 21:45:32 +0000401
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000402\begin{methoddesc}[GNUTranslations]{lgettext}{message}
403Equivalent to \method{gettext()}, but the translation is returned
404in the preferred system encoding, if no other encoding was explicitly
405set with \method{set_output_charset()}.
406
407\versionadded{2.4}
408\end{methoddesc}
409
Barry Warsaw50889232003-04-24 18:14:49 +0000410\begin{methoddesc}[GNUTranslations]{ugettext}{message}
411Look up the \var{message} id in the catalog and return the
412corresponding message string, as a Unicode string. If there is no
413entry in the catalog for the \var{message} id, and a fallback has been
414set, the look up is forwarded to the fallback's \method{ugettext()}
415method. Otherwise, the \var{message} id is returned.
416\end{methoddesc}
417
418\begin{methoddesc}[GNUTranslations]{ngettext}{singular, plural, n}
419Do a plural-forms lookup of a message id. \var{singular} is used as
420the message id for purposes of lookup in the catalog, while \var{n} is
421used to determine which plural form to use. The returned message
422string is an 8-bit string encoded with the catalog's charset encoding,
423if known.
424
425If the message id is not found in the catalog, and a fallback is
426specified, the request is forwarded to the fallback's
427\method{ngettext()} method. Otherwise, when \var{n} is 1 \var{singular} is
428returned, and \var{plural} is returned in all other cases.
429
430\versionadded{2.3}
431\end{methoddesc}
432
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000433\begin{methoddesc}[GNUTranslations]{lngettext}{singular, plural, n}
434Equivalent to \method{gettext()}, but the translation is returned
435in the preferred system encoding, if no other encoding was explicitly
436set with \method{set_output_charset()}.
437
438\versionadded{2.4}
439\end{methoddesc}
440
Barry Warsaw50889232003-04-24 18:14:49 +0000441\begin{methoddesc}[GNUTranslations]{ungettext}{singular, plural, n}
442Do a plural-forms lookup of a message id. \var{singular} is used as
443the message id for purposes of lookup in the catalog, while \var{n} is
444used to determine which plural form to use. The returned message
445string is a Unicode string.
446
447If the message id is not found in the catalog, and a fallback is
448specified, the request is forwarded to the fallback's
449\method{ungettext()} method. Otherwise, when \var{n} is 1 \var{singular} is
450returned, and \var{plural} is returned in all other cases.
451
452Here is an example:
453
454\begin{verbatim}
455n = len(os.listdir('.'))
456cat = GNUTranslations(somefile)
457message = cat.ungettext(
458 'There is %(num)d file in this directory',
459 'There are %(num)d files in this directory',
Andrew M. Kuchling099bd522004-07-10 16:01:10 +0000460 n) % {'num': n}
Barry Warsaw50889232003-04-24 18:14:49 +0000461\end{verbatim}
462
463\versionadded{2.3}
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000464\end{methoddesc}
465
Fred Draked0726c32000-09-07 18:55:08 +0000466\subsubsection{Solaris message catalog support}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000467
468The Solaris operating system defines its own binary
469\file{.mo} file format, but since no documentation can be found on
470this format, it is not supported at this time.
471
472\subsubsection{The Catalog constructor}
473
Fred Draked0726c32000-09-07 18:55:08 +0000474GNOME\index{GNOME} uses a version of the \module{gettext} module by
475James Henstridge, but this version has a slightly different API. Its
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000476documented usage was:
477
478\begin{verbatim}
479import gettext
480cat = gettext.Catalog(domain, localedir)
481_ = cat.gettext
482print _('hello world')
483\end{verbatim}
484
485For compatibility with this older module, the function
Raymond Hettingerf17d65d2003-08-12 00:01:16 +0000486\function{Catalog()} is an alias for the \function{translation()}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000487function described above.
488
489One difference between this module and Henstridge's: his catalog
490objects supported access through a mapping API, but this appears to be
491unused and so is not currently supported.
492
493\subsection{Internationalizing your programs and modules}
494Internationalization (I18N) refers to the operation by which a program
495is made aware of multiple languages. Localization (L10N) refers to
496the adaptation of your program, once internationalized, to the local
497language and cultural habits. In order to provide multilingual
498messages for your Python programs, you need to take the following
499steps:
500
501\begin{enumerate}
502 \item prepare your program or module by specially marking
503 translatable strings
504 \item run a suite of tools over your marked files to generate raw
505 messages catalogs
506 \item create language specific translations of the message catalogs
507 \item use the \module{gettext} module so that message strings are
508 properly translated
509\end{enumerate}
510
511In order to prepare your code for I18N, you need to look at all the
512strings in your files. Any string that needs to be translated
Fred Drake91f2f262001-07-06 19:28:48 +0000513should be marked by wrapping it in \code{_('...')} --- that is, a call
514to the function \function{_()}. For example:
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000515
516\begin{verbatim}
517filename = 'mylog.txt'
518message = _('writing a log message')
519fp = open(filename, 'w')
520fp.write(message)
521fp.close()
522\end{verbatim}
523
Fred Draked576e9d2000-08-30 04:19:20 +0000524In this example, the string \code{'writing a log message'} is marked as
525a candidate for translation, while the strings \code{'mylog.txt'} and
526\code{'w'} are not.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000527
Barry Warsawb4162902001-01-31 21:21:45 +0000528The Python distribution comes with two tools which help you generate
529the message catalogs once you've prepared your source code. These may
530or may not be available from a binary distribution, but they can be
531found in a source distribution, in the \file{Tools/i18n} directory.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000532
Barry Warsawb4162902001-01-31 21:21:45 +0000533The \program{pygettext}\footnote{Fran\c cois Pinard has
534written a program called
Barry Warsawddef8882000-09-13 12:04:47 +0000535\program{xpot} which does a similar job. It is available as part of
536his \program{po-utils} package at
Fred Drakeef139492003-07-22 00:49:11 +0000537\url{http://www.iro.umontreal.ca/contrib/po-utils/HTML/}.} program
Barry Warsawb4162902001-01-31 21:21:45 +0000538scans all your Python source code looking for the strings you
539previously marked as translatable. It is similar to the GNU
540\program{gettext} program except that it understands all the
Fred Drake2884d6d2003-07-02 12:27:43 +0000541intricacies of Python source code, but knows nothing about C or \Cpp
Barry Warsawb4162902001-01-31 21:21:45 +0000542source code. You don't need GNU \code{gettext} unless you're also
Fred Drake91f2f262001-07-06 19:28:48 +0000543going to be translating C code (such as C extension modules).
Barry Warsawb4162902001-01-31 21:21:45 +0000544
545\program{pygettext} generates textual Uniforum-style human readable
546message catalog \file{.pot} files, essentially structured human
547readable files which contain every marked string in the source code,
548along with a placeholder for the translation strings.
549\program{pygettext} is a command line script that supports a similar
550command line interface as \program{xgettext}; for details on its use,
551run:
552
553\begin{verbatim}
554pygettext.py --help
555\end{verbatim}
556
557Copies of these \file{.pot} files are then handed over to the
558individual human translators who write language-specific versions for
559every supported natural language. They send you back the filled in
560language-specific versions as a \file{.po} file. Using the
561\program{msgfmt.py}\footnote{\program{msgfmt.py} is binary
562compatible with GNU \program{msgfmt} except that it provides a
563simpler, all-Python implementation. With this and
564\program{pygettext.py}, you generally won't need to install the GNU
565\program{gettext} package to internationalize your Python
566applications.} program (in the \file{Tools/i18n} directory), you take the
567\file{.po} files from your translators and generate the
568machine-readable \file{.mo} binary catalog files. The \file{.mo}
569files are what the \module{gettext} module uses for the actual
570translation processing during run-time.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000571
572How you use the \module{gettext} module in your code depends on
573whether you are internationalizing your entire application or a single
574module.
575
576\subsubsection{Localizing your module}
577
578If you are localizing your module, you must take care not to make
579global changes, e.g. to the built-in namespace. You should not use
Fred Draked576e9d2000-08-30 04:19:20 +0000580the GNU \code{gettext} API but instead the class-based API.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000581
582Let's say your module is called ``spam'' and the module's various
583natural language translation \file{.mo} files reside in
Fred Draked576e9d2000-08-30 04:19:20 +0000584\file{/usr/share/locale} in GNU \program{gettext} format. Here's what
585you would put at the top of your module:
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000586
587\begin{verbatim}
588import gettext
589t = gettext.translation('spam', '/usr/share/locale')
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000590_ = t.lgettext
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000591\end{verbatim}
592
593If your translators were providing you with Unicode strings in their
594\file{.po} files, you'd instead do:
595
596\begin{verbatim}
597import gettext
598t = gettext.translation('spam', '/usr/share/locale')
599_ = t.ugettext
600\end{verbatim}
601
602\subsubsection{Localizing your application}
603
604If you are localizing your application, you can install the \function{_()}
605function globally into the built-in namespace, usually in the main driver file
606of your application. This will let all your application-specific
607files just use \code{_('...')} without having to explicitly install it in
608each file.
609
610In the simple case then, you need only add the following bit of code
611to the main driver file of your application:
612
613\begin{verbatim}
614import gettext
615gettext.install('myapplication')
616\end{verbatim}
617
Fred Draked576e9d2000-08-30 04:19:20 +0000618If you need to set the locale directory or the \var{unicode} flag,
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000619you can pass these into the \function{install()} function:
620
621\begin{verbatim}
622import gettext
623gettext.install('myapplication', '/usr/share/locale', unicode=1)
624\end{verbatim}
625
626\subsubsection{Changing languages on the fly}
627
628If your program needs to support many languages at the same time, you
629may want to create multiple translation instances and then switch
630between them explicitly, like so:
631
632\begin{verbatim}
633import gettext
634
Johannes Gijsbers2014c032004-09-11 17:33:25 +0000635lang1 = gettext.translation('myapplication', languages=['en'])
636lang2 = gettext.translation('myapplication', languages=['fr'])
637lang3 = gettext.translation('myapplication', languages=['de'])
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000638
639# start by using language1
640lang1.install()
641
642# ... time goes by, user selects language 2
643lang2.install()
644
645# ... more time goes by, user selects language 3
646lang3.install()
647\end{verbatim}
648
649\subsubsection{Deferred translations}
650
Neal Norwitz563d12d2002-06-24 02:22:39 +0000651In most coding situations, strings are translated where they are coded.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000652Occasionally however, you need to mark strings for translation, but
653defer actual translation until later. A classic example is:
654
655\begin{verbatim}
656animals = ['mollusk',
657 'albatross',
658 'rat',
659 'penguin',
660 'python',
661 ]
662# ...
663for a in animals:
664 print a
665\end{verbatim}
666
667Here, you want to mark the strings in the \code{animals} list as being
668translatable, but you don't actually want to translate them until they
669are printed.
670
671Here is one way you can handle this situation:
672
673\begin{verbatim}
674def _(message): return message
675
676animals = [_('mollusk'),
677 _('albatross'),
678 _('rat'),
679 _('penguin'),
680 _('python'),
681 ]
682
683del _
684
685# ...
686for a in animals:
687 print _(a)
688\end{verbatim}
689
690This works because the dummy definition of \function{_()} simply returns
691the string unchanged. And this dummy definition will temporarily
692override any definition of \function{_()} in the built-in namespace
Fred Draked576e9d2000-08-30 04:19:20 +0000693(until the \keyword{del} command).
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000694Take care, though if you have a previous definition of \function{_} in
695the local namespace.
696
697Note that the second use of \function{_()} will not identify ``a'' as
698being translatable to the \program{pygettext} program, since it is not
699a string.
700
701Another way to handle this is with the following example:
702
703\begin{verbatim}
704def N_(message): return message
705
706animals = [N_('mollusk'),
707 N_('albatross'),
708 N_('rat'),
709 N_('penguin'),
710 N_('python'),
711 ]
712
713# ...
714for a in animals:
715 print _(a)
716\end{verbatim}
717
718In this case, you are marking translatable strings with the function
Fred Draked576e9d2000-08-30 04:19:20 +0000719\function{N_()},\footnote{The choice of \function{N_()} here is totally
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000720arbitrary; it could have just as easily been
Fred Draked576e9d2000-08-30 04:19:20 +0000721\function{MarkThisStringForTranslation()}.
722} which won't conflict with any definition of
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000723\function{_()}. However, you will need to teach your message extraction
724program to look for translatable strings marked with \function{N_()}.
725\program{pygettext} and \program{xpot} both support this through the
726use of command line switches.
727
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000728\subsubsection{\function{gettext()} vs. \function{lgettext()}}
729In Python 2.4 the \function{lgettext()} family of functions were
730introduced. The intention of these functions is to provide an
731alternative which is more compliant with the current
732implementation of GNU gettext. Unlike \function{gettext()}, which
733returns strings encoded with the same codeset used in the
734translation file, \function{lgettext()} will return strings
735encoded with the preferred system encoding, as returned by
736\function{locale.getpreferredencoding()}. Also notice that
737Python 2.4 introduces new functions to explicitly choose
738the codeset used in translated strings. If a codeset is explicitly
739set, even \function{lgettext()} will return translated strings in
740the requested codeset, as would be expected in the GNU gettext
741implementation.
742
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000743\subsection{Acknowledgements}
744
745The following people contributed code, feedback, design suggestions,
746previous implementations, and valuable experience to the creation of
747this module:
748
749\begin{itemize}
750 \item Peter Funk
751 \item James Henstridge
Fred Drake74f5a562002-11-22 14:28:53 +0000752 \item Juan David Ib\'a\~nez Palomar
Fred Draked576e9d2000-08-30 04:19:20 +0000753 \item Marc-Andr\'e Lemburg
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000754 \item Martin von L\"owis
755 \item Fran\c cois Pinard
756 \item Barry Warsaw
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000757 \item Gustavo Niemeyer
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000758\end{itemize}