blob: ace719f8a713c998527409703704cc5b55831483 [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.}
Barry Warsawa770e862001-01-15 17:08:45 +00006\moduleauthor{Barry A. Warsaw}{barry@digicool.com}
7\sectionauthor{Barry A. Warsaw}{barry@digicool.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
Fred Draked576e9d2000-08-30 04:19:20 +000054\begin{funcdesc}{textdomain}{\optional{domain}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +000055Change or query the current global domain. If \var{domain} is
56\code{None}, then the current global domain is returned, otherwise the
57global domain is set to \var{domain}, which is returned.
58\end{funcdesc}
59
60\begin{funcdesc}{gettext}{message}
61Return the localized translation of \var{message}, based on the
62current global domain, language, and locale directory. This function
63is usually aliased as \function{_} in the local namespace (see
64examples below).
65\end{funcdesc}
66
67\begin{funcdesc}{dgettext}{domain, message}
68Like \function{gettext()}, but look the message up in the specified
69\var{domain}.
70\end{funcdesc}
71
Martin v. Löwisd8996052002-11-21 21:45:32 +000072\begin{funcdesc}{ngettext}{singular, plural, n}
73
74Like \function{gettext()}, but consider plural forms. If a translation
75is found, apply the plural formula to \var{n}, and return the
76resulting message (some languages have more than two plural forms).
77If no translation is found, return \var{singular} if \var{n} is 1;
78return \var{plural} otherwise.
79
80The Plural formula is taken from the catalog header. It is a C or
81Python expression that has a free variable n; the expression evaluates
82to the index of the plural in the catalog. See the GNU gettext
83documentation for the precise syntax to be used in .po files, and the
84formulas for a variety of languages.
85
86\versionadded{2.3}
87
88\end{funcdesc}
89
90\begin{funcdesc}{dngettext}{domain, singular, plural, n}
91Like \function{ngettext()}, but look the message up in the specified
92\var{domain}.
93
94\versionadded{2.3}
95\end{funcdesc}
96
97
Barry Warsaw0691a6b2000-08-30 03:27:10 +000098Note that GNU \program{gettext} also defines a \function{dcgettext()}
99method, but this was deemed not useful and so it is currently
100unimplemented.
101
102Here's an example of typical usage for this API:
103
104\begin{verbatim}
105import gettext
106gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
107gettext.textdomain('myapplication')
108_ = gettext.gettext
109# ...
110print _('This is a translatable string.')
111\end{verbatim}
112
113\subsection{Class-based API}
114
115The class-based API of the \module{gettext} module gives you more
116flexibility and greater convenience than the GNU \program{gettext}
117API. It is the recommended way of localizing your Python applications and
118modules. \module{gettext} defines a ``translations'' class which
119implements the parsing of GNU \file{.mo} format files, and has methods
120for returning either standard 8-bit strings or Unicode strings.
121Translations instances can also install themselves in the built-in
122namespace as the function \function{_()}.
123
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000124\begin{funcdesc}{find}{domain\optional{, localedir\optional{,
125 languages\optional{, all}}}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000126This function implements the standard \file{.mo} file search
127algorithm. It takes a \var{domain}, identical to what
Barry Warsaw91b81c42001-10-18 19:41:48 +0000128\function{textdomain()} takes. Optional \var{localedir} is as in
129\function{bindtextdomain()} Optional \var{languages} is a list of
130strings, where each string is a language code.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000131
132If \var{localedir} is not given, then the default system locale
Fred Draked576e9d2000-08-30 04:19:20 +0000133directory is used.\footnote{See the footnote for
134\function{bindtextdomain()} above.} If \var{languages} is not given,
135then the following environment variables are searched: \envvar{LANGUAGE},
136\envvar{LC_ALL}, \envvar{LC_MESSAGES}, and \envvar{LANG}. The first one
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000137returning a non-empty value is used for the \var{languages} variable.
Barry Warsaw91b81c42001-10-18 19:41:48 +0000138The environment variables should contain a colon separated list of
139languages, which will be split on the colon to produce the expected
140list of language code strings.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000141
142\function{find()} then expands and normalizes the languages, and then
143iterates through them, searching for an existing file built of these
144components:
145
146\file{\var{localedir}/\var{language}/LC_MESSAGES/\var{domain}.mo}
147
148The first such file name that exists is returned by \function{find()}.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000149If no such file is found, then \code{None} is returned. If \var{all}
150is given, it returns a list of all file names, in the order in which
151they appear in the languages list or the environment variables.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000152\end{funcdesc}
153
Fred Draked576e9d2000-08-30 04:19:20 +0000154\begin{funcdesc}{translation}{domain\optional{, localedir\optional{,
Martin v. Löwis1be64192002-01-11 06:33:28 +0000155 languages\optional{,
156 class_,\optional{fallback}}}}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000157Return a \class{Translations} instance based on the \var{domain},
158\var{localedir}, and \var{languages}, which are first passed to
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000159\function{find()} to get a list of the
160associated \file{.mo} file paths. Instances with
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000161identical \file{.mo} file names are cached. The actual class instantiated
162is either \var{class_} if provided, otherwise
163\class{GNUTranslations}. The class's constructor must take a single
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000164file object argument.
165
166If multiple files are found, later files are used as fallbacks for
167earlier ones. To allow setting the fallback, \function{copy.copy}
168is used to clone each translation object from the cache; the actual
169instance data is still shared with the cache.
170
171If no \file{.mo} file is found, this function raises
172\exception{IOError} if \var{fallback} is false (which is the default),
173and returns a \class{NullTranslations} instance if \var{fallback} is
174true.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000175\end{funcdesc}
176
Fred Draked576e9d2000-08-30 04:19:20 +0000177\begin{funcdesc}{install}{domain\optional{, localedir\optional{, unicode}}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000178This installs the function \function{_} in Python's builtin namespace,
179based on \var{domain}, and \var{localedir} which are passed to the
180function \function{translation()}. The \var{unicode} flag is passed to
181the resulting translation object's \method{install} method.
182
183As seen below, you usually mark the strings in your application that are
Fred Drake91f2f262001-07-06 19:28:48 +0000184candidates for translation, by wrapping them in a call to the
185\function{_()} function, like this:
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000186
187\begin{verbatim}
188print _('This string will be translated.')
189\end{verbatim}
190
191For convenience, you want the \function{_()} function to be installed in
192Python's builtin namespace, so it is easily accessible in all modules
193of your application.
194\end{funcdesc}
195
196\subsubsection{The \class{NullTranslations} class}
197Translation classes are what actually implement the translation of
198original source file message strings to translated message strings.
199The base class used by all translation classes is
200\class{NullTranslations}; this provides the basic interface you can use
201to write your own specialized translation classes. Here are the
202methods of \class{NullTranslations}:
203
Fred Draked576e9d2000-08-30 04:19:20 +0000204\begin{methoddesc}[NullTranslations]{__init__}{\optional{fp}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000205Takes an optional file object \var{fp}, which is ignored by the base
206class. Initializes ``protected'' instance variables \var{_info} and
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000207\var{_charset} which are set by derived classes, as well as \var{_fallback},
208which is set through \method{add_fallback}. It then calls
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000209\code{self._parse(fp)} if \var{fp} is not \code{None}.
210\end{methoddesc}
211
212\begin{methoddesc}[NullTranslations]{_parse}{fp}
213No-op'd in the base class, this method takes file object \var{fp}, and
214reads the data from the file, initializing its message catalog. If
215you have an unsupported message catalog file format, you should
216override this method to parse your format.
217\end{methoddesc}
218
Martin v. Löwiscebcc612003-08-05 05:54:15 +0000219\begin{methoddesc}[NullTranslations]{add_fallback}{fallback}
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000220Add \var{fallback} as the fallback object for the current translation
221object. A translation object should consult the fallback if it cannot
222provide a translation for a given message.
223\end{methoddesc}
224
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000225\begin{methoddesc}[NullTranslations]{gettext}{message}
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000226If a fallback has been set, forward \method{gettext} to the fallback.
227Otherwise, return the translated message. Overridden in derived classes.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000228\end{methoddesc}
229
230\begin{methoddesc}[NullTranslations]{ugettext}{message}
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000231If a fallback has been set, forward \method{ugettext} to the fallback.
232Otherwise, return the translated message as a Unicode string.
233Overridden in derived classes.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000234\end{methoddesc}
235
Martin v. Löwisd8996052002-11-21 21:45:32 +0000236\begin{methoddesc}[NullTranslations]{ngettext}{singular, plural, n}
237If a fallback has been set, forward \method{ngettext} to the fallback.
238Otherwise, return the translated message. Overridden in derived classes.
239
240\versionadded{2.3}
241\end{methoddesc}
242
243\begin{methoddesc}[NullTranslations]{ungettext}{singular, plural, n}
244If a fallback has been set, forward \method{ungettext} to the fallback.
245Otherwise, return the translated message as a Unicode string.
246Overridden in derived classes.
247
248\versionadded{2.3}
249\end{methoddesc}
250
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000251\begin{methoddesc}[NullTranslations]{info}{}
Fred Draked576e9d2000-08-30 04:19:20 +0000252Return the ``protected'' \member{_info} variable.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000253\end{methoddesc}
254
255\begin{methoddesc}[NullTranslations]{charset}{}
Fred Draked576e9d2000-08-30 04:19:20 +0000256Return the ``protected'' \member{_charset} variable.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000257\end{methoddesc}
258
Fred Draked576e9d2000-08-30 04:19:20 +0000259\begin{methoddesc}[NullTranslations]{install}{\optional{unicode}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000260If the \var{unicode} flag is false, this method installs
Fred Draked576e9d2000-08-30 04:19:20 +0000261\method{self.gettext()} into the built-in namespace, binding it to
262\samp{_}. If \var{unicode} is true, it binds \method{self.ugettext()}
263instead. By default, \var{unicode} is false.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000264
265Note that this is only one way, albeit the most convenient way, to
266make the \function{_} function available to your application. Because it
267affects the entire application globally, and specifically the built-in
268namespace, localized modules should never install \function{_}.
269Instead, they should use this code to make \function{_} available to
270their module:
271
272\begin{verbatim}
273import gettext
274t = gettext.translation('mymodule', ...)
275_ = t.gettext
276\end{verbatim}
277
278This puts \function{_} only in the module's global namespace and so
279only affects calls within this module.
280\end{methoddesc}
281
282\subsubsection{The \class{GNUTranslations} class}
283
284The \module{gettext} module provides one additional class derived from
285\class{NullTranslations}: \class{GNUTranslations}. This class
286overrides \method{_parse()} to enable reading GNU \program{gettext}
287format \file{.mo} files in both big-endian and little-endian format.
Barry Warsaw50889232003-04-24 18:14:49 +0000288It also coerces both message ids and message strings to Unicode.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000289
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000290\class{GNUTranslations} parses optional meta-data out of the
291translation catalog. It is convention with GNU \program{gettext} to
292include meta-data as the translation for the empty string. This
Barry Warsaw50889232003-04-24 18:14:49 +0000293meta-data is in \rfc{822}-style \code{key: value} pairs, and should
294contain the \code{Project-Id-Version} key. If the key
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000295\code{Content-Type} is found, then the \code{charset} property is used
296to initialize the ``protected'' \member{_charset} instance variable,
Barry Warsaw50889232003-04-24 18:14:49 +0000297defaulting to \code{None} if not found. If the charset encoding is
298specified, then all message ids and message strings read from the
299catalog are converted to Unicode using this encoding. The
300\method{ugettext()} method always returns a Unicode, while the
301\method{gettext()} returns an encoded 8-bit string. For the message
302id arguments of both methods, either Unicode strings or 8-bit strings
303containing only US-ASCII characters are acceptable. Note that the
304Unicode version of the methods (i.e. \method{ugettext()} and
305\method{ungettext()}) are the recommended interface to use for
306internationalized Python programs.
307
308The entire set of key/value pairs are placed into a dictionary and set
309as the ``protected'' \member{_info} instance variable.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000310
311If the \file{.mo} file's magic number is invalid, or if other problems
312occur while reading the file, instantiating a \class{GNUTranslations} class
313can raise \exception{IOError}.
314
Barry Warsaw50889232003-04-24 18:14:49 +0000315The following methods are overridden from the base class implementation:
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000316
Barry Warsaw50889232003-04-24 18:14:49 +0000317\begin{methoddesc}[GNUTranslations]{gettext}{message}
318Look up the \var{message} id in the catalog and return the
319corresponding message string, as an 8-bit string encoded with the
320catalog's charset encoding, if known. If there is no entry in the
321catalog for the \var{message} id, and a fallback has been set, the
322look up is forwarded to the fallback's \method{gettext()} method.
323Otherwise, the \var{message} id is returned.
324\end{methoddesc}
Martin v. Löwisd8996052002-11-21 21:45:32 +0000325
Barry Warsaw50889232003-04-24 18:14:49 +0000326\begin{methoddesc}[GNUTranslations]{ugettext}{message}
327Look up the \var{message} id in the catalog and return the
328corresponding message string, as a Unicode string. If there is no
329entry in the catalog for the \var{message} id, and a fallback has been
330set, the look up is forwarded to the fallback's \method{ugettext()}
331method. Otherwise, the \var{message} id is returned.
332\end{methoddesc}
333
334\begin{methoddesc}[GNUTranslations]{ngettext}{singular, plural, n}
335Do a plural-forms lookup of a message id. \var{singular} is used as
336the message id for purposes of lookup in the catalog, while \var{n} is
337used to determine which plural form to use. The returned message
338string is an 8-bit string encoded with the catalog's charset encoding,
339if known.
340
341If the message id is not found in the catalog, and a fallback is
342specified, the request is forwarded to the fallback's
343\method{ngettext()} method. Otherwise, when \var{n} is 1 \var{singular} is
344returned, and \var{plural} is returned in all other cases.
345
346\versionadded{2.3}
347\end{methoddesc}
348
349\begin{methoddesc}[GNUTranslations]{ungettext}{singular, plural, n}
350Do a plural-forms lookup of a message id. \var{singular} is used as
351the message id for purposes of lookup in the catalog, while \var{n} is
352used to determine which plural form to use. The returned message
353string is a Unicode string.
354
355If the message id is not found in the catalog, and a fallback is
356specified, the request is forwarded to the fallback's
357\method{ungettext()} method. Otherwise, when \var{n} is 1 \var{singular} is
358returned, and \var{plural} is returned in all other cases.
359
360Here is an example:
361
362\begin{verbatim}
363n = len(os.listdir('.'))
364cat = GNUTranslations(somefile)
365message = cat.ungettext(
366 'There is %(num)d file in this directory',
367 'There are %(num)d files in this directory',
368 n) % {'n': n}
369\end{verbatim}
370
371\versionadded{2.3}
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000372\end{methoddesc}
373
Fred Draked0726c32000-09-07 18:55:08 +0000374\subsubsection{Solaris message catalog support}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000375
376The Solaris operating system defines its own binary
377\file{.mo} file format, but since no documentation can be found on
378this format, it is not supported at this time.
379
380\subsubsection{The Catalog constructor}
381
Fred Draked0726c32000-09-07 18:55:08 +0000382GNOME\index{GNOME} uses a version of the \module{gettext} module by
383James Henstridge, but this version has a slightly different API. Its
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000384documented usage was:
385
386\begin{verbatim}
387import gettext
388cat = gettext.Catalog(domain, localedir)
389_ = cat.gettext
390print _('hello world')
391\end{verbatim}
392
393For compatibility with this older module, the function
394\function{Catalog()} is an alias for the the \function{translation()}
395function described above.
396
397One difference between this module and Henstridge's: his catalog
398objects supported access through a mapping API, but this appears to be
399unused and so is not currently supported.
400
401\subsection{Internationalizing your programs and modules}
402Internationalization (I18N) refers to the operation by which a program
403is made aware of multiple languages. Localization (L10N) refers to
404the adaptation of your program, once internationalized, to the local
405language and cultural habits. In order to provide multilingual
406messages for your Python programs, you need to take the following
407steps:
408
409\begin{enumerate}
410 \item prepare your program or module by specially marking
411 translatable strings
412 \item run a suite of tools over your marked files to generate raw
413 messages catalogs
414 \item create language specific translations of the message catalogs
415 \item use the \module{gettext} module so that message strings are
416 properly translated
417\end{enumerate}
418
419In order to prepare your code for I18N, you need to look at all the
420strings in your files. Any string that needs to be translated
Fred Drake91f2f262001-07-06 19:28:48 +0000421should be marked by wrapping it in \code{_('...')} --- that is, a call
422to the function \function{_()}. For example:
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000423
424\begin{verbatim}
425filename = 'mylog.txt'
426message = _('writing a log message')
427fp = open(filename, 'w')
428fp.write(message)
429fp.close()
430\end{verbatim}
431
Fred Draked576e9d2000-08-30 04:19:20 +0000432In this example, the string \code{'writing a log message'} is marked as
433a candidate for translation, while the strings \code{'mylog.txt'} and
434\code{'w'} are not.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000435
Barry Warsawb4162902001-01-31 21:21:45 +0000436The Python distribution comes with two tools which help you generate
437the message catalogs once you've prepared your source code. These may
438or may not be available from a binary distribution, but they can be
439found in a source distribution, in the \file{Tools/i18n} directory.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000440
Barry Warsawb4162902001-01-31 21:21:45 +0000441The \program{pygettext}\footnote{Fran\c cois Pinard has
442written a program called
Barry Warsawddef8882000-09-13 12:04:47 +0000443\program{xpot} which does a similar job. It is available as part of
444his \program{po-utils} package at
Fred Drakeef139492003-07-22 00:49:11 +0000445\url{http://www.iro.umontreal.ca/contrib/po-utils/HTML/}.} program
Barry Warsawb4162902001-01-31 21:21:45 +0000446scans all your Python source code looking for the strings you
447previously marked as translatable. It is similar to the GNU
448\program{gettext} program except that it understands all the
Fred Drake2884d6d2003-07-02 12:27:43 +0000449intricacies of Python source code, but knows nothing about C or \Cpp
Barry Warsawb4162902001-01-31 21:21:45 +0000450source code. You don't need GNU \code{gettext} unless you're also
Fred Drake91f2f262001-07-06 19:28:48 +0000451going to be translating C code (such as C extension modules).
Barry Warsawb4162902001-01-31 21:21:45 +0000452
453\program{pygettext} generates textual Uniforum-style human readable
454message catalog \file{.pot} files, essentially structured human
455readable files which contain every marked string in the source code,
456along with a placeholder for the translation strings.
457\program{pygettext} is a command line script that supports a similar
458command line interface as \program{xgettext}; for details on its use,
459run:
460
461\begin{verbatim}
462pygettext.py --help
463\end{verbatim}
464
465Copies of these \file{.pot} files are then handed over to the
466individual human translators who write language-specific versions for
467every supported natural language. They send you back the filled in
468language-specific versions as a \file{.po} file. Using the
469\program{msgfmt.py}\footnote{\program{msgfmt.py} is binary
470compatible with GNU \program{msgfmt} except that it provides a
471simpler, all-Python implementation. With this and
472\program{pygettext.py}, you generally won't need to install the GNU
473\program{gettext} package to internationalize your Python
474applications.} program (in the \file{Tools/i18n} directory), you take the
475\file{.po} files from your translators and generate the
476machine-readable \file{.mo} binary catalog files. The \file{.mo}
477files are what the \module{gettext} module uses for the actual
478translation processing during run-time.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000479
480How you use the \module{gettext} module in your code depends on
481whether you are internationalizing your entire application or a single
482module.
483
484\subsubsection{Localizing your module}
485
486If you are localizing your module, you must take care not to make
487global changes, e.g. to the built-in namespace. You should not use
Fred Draked576e9d2000-08-30 04:19:20 +0000488the GNU \code{gettext} API but instead the class-based API.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000489
490Let's say your module is called ``spam'' and the module's various
491natural language translation \file{.mo} files reside in
Fred Draked576e9d2000-08-30 04:19:20 +0000492\file{/usr/share/locale} in GNU \program{gettext} format. Here's what
493you would put at the top of your module:
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000494
495\begin{verbatim}
496import gettext
497t = gettext.translation('spam', '/usr/share/locale')
498_ = t.gettext
499\end{verbatim}
500
501If your translators were providing you with Unicode strings in their
502\file{.po} files, you'd instead do:
503
504\begin{verbatim}
505import gettext
506t = gettext.translation('spam', '/usr/share/locale')
507_ = t.ugettext
508\end{verbatim}
509
510\subsubsection{Localizing your application}
511
512If you are localizing your application, you can install the \function{_()}
513function globally into the built-in namespace, usually in the main driver file
514of your application. This will let all your application-specific
515files just use \code{_('...')} without having to explicitly install it in
516each file.
517
518In the simple case then, you need only add the following bit of code
519to the main driver file of your application:
520
521\begin{verbatim}
522import gettext
523gettext.install('myapplication')
524\end{verbatim}
525
Fred Draked576e9d2000-08-30 04:19:20 +0000526If you need to set the locale directory or the \var{unicode} flag,
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000527you can pass these into the \function{install()} function:
528
529\begin{verbatim}
530import gettext
531gettext.install('myapplication', '/usr/share/locale', unicode=1)
532\end{verbatim}
533
534\subsubsection{Changing languages on the fly}
535
536If your program needs to support many languages at the same time, you
537may want to create multiple translation instances and then switch
538between them explicitly, like so:
539
540\begin{verbatim}
541import gettext
542
543lang1 = gettext.translation(languages=['en'])
544lang2 = gettext.translation(languages=['fr'])
545lang3 = gettext.translation(languages=['de'])
546
547# start by using language1
548lang1.install()
549
550# ... time goes by, user selects language 2
551lang2.install()
552
553# ... more time goes by, user selects language 3
554lang3.install()
555\end{verbatim}
556
557\subsubsection{Deferred translations}
558
Neal Norwitz563d12d2002-06-24 02:22:39 +0000559In most coding situations, strings are translated where they are coded.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000560Occasionally however, you need to mark strings for translation, but
561defer actual translation until later. A classic example is:
562
563\begin{verbatim}
564animals = ['mollusk',
565 'albatross',
566 'rat',
567 'penguin',
568 'python',
569 ]
570# ...
571for a in animals:
572 print a
573\end{verbatim}
574
575Here, you want to mark the strings in the \code{animals} list as being
576translatable, but you don't actually want to translate them until they
577are printed.
578
579Here is one way you can handle this situation:
580
581\begin{verbatim}
582def _(message): return message
583
584animals = [_('mollusk'),
585 _('albatross'),
586 _('rat'),
587 _('penguin'),
588 _('python'),
589 ]
590
591del _
592
593# ...
594for a in animals:
595 print _(a)
596\end{verbatim}
597
598This works because the dummy definition of \function{_()} simply returns
599the string unchanged. And this dummy definition will temporarily
600override any definition of \function{_()} in the built-in namespace
Fred Draked576e9d2000-08-30 04:19:20 +0000601(until the \keyword{del} command).
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000602Take care, though if you have a previous definition of \function{_} in
603the local namespace.
604
605Note that the second use of \function{_()} will not identify ``a'' as
606being translatable to the \program{pygettext} program, since it is not
607a string.
608
609Another way to handle this is with the following example:
610
611\begin{verbatim}
612def N_(message): return message
613
614animals = [N_('mollusk'),
615 N_('albatross'),
616 N_('rat'),
617 N_('penguin'),
618 N_('python'),
619 ]
620
621# ...
622for a in animals:
623 print _(a)
624\end{verbatim}
625
626In this case, you are marking translatable strings with the function
Fred Draked576e9d2000-08-30 04:19:20 +0000627\function{N_()},\footnote{The choice of \function{N_()} here is totally
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000628arbitrary; it could have just as easily been
Fred Draked576e9d2000-08-30 04:19:20 +0000629\function{MarkThisStringForTranslation()}.
630} which won't conflict with any definition of
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000631\function{_()}. However, you will need to teach your message extraction
632program to look for translatable strings marked with \function{N_()}.
633\program{pygettext} and \program{xpot} both support this through the
634use of command line switches.
635
636\subsection{Acknowledgements}
637
638The following people contributed code, feedback, design suggestions,
639previous implementations, and valuable experience to the creation of
640this module:
641
642\begin{itemize}
643 \item Peter Funk
644 \item James Henstridge
Fred Drake74f5a562002-11-22 14:28:53 +0000645 \item Juan David Ib\'a\~nez Palomar
Fred Draked576e9d2000-08-30 04:19:20 +0000646 \item Marc-Andr\'e Lemburg
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000647 \item Martin von L\"owis
648 \item Fran\c cois Pinard
649 \item Barry Warsaw
650\end{itemize}