blob: aaacd80551f6ea8a65c021384a7a64ffaf0111e0 [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
72Note that GNU \program{gettext} also defines a \function{dcgettext()}
73method, but this was deemed not useful and so it is currently
74unimplemented.
75
76Here's an example of typical usage for this API:
77
78\begin{verbatim}
79import gettext
80gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
81gettext.textdomain('myapplication')
82_ = gettext.gettext
83# ...
84print _('This is a translatable string.')
85\end{verbatim}
86
87\subsection{Class-based API}
88
89The class-based API of the \module{gettext} module gives you more
90flexibility and greater convenience than the GNU \program{gettext}
91API. It is the recommended way of localizing your Python applications and
92modules. \module{gettext} defines a ``translations'' class which
93implements the parsing of GNU \file{.mo} format files, and has methods
94for returning either standard 8-bit strings or Unicode strings.
95Translations instances can also install themselves in the built-in
96namespace as the function \function{_()}.
97
Fred Draked576e9d2000-08-30 04:19:20 +000098\begin{funcdesc}{find}{domain\optional{, localedir\optional{, languages}}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +000099This function implements the standard \file{.mo} file search
100algorithm. It takes a \var{domain}, identical to what
Barry Warsaw91b81c42001-10-18 19:41:48 +0000101\function{textdomain()} takes. Optional \var{localedir} is as in
102\function{bindtextdomain()} Optional \var{languages} is a list of
103strings, where each string is a language code.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000104
105If \var{localedir} is not given, then the default system locale
Fred Draked576e9d2000-08-30 04:19:20 +0000106directory is used.\footnote{See the footnote for
107\function{bindtextdomain()} above.} If \var{languages} is not given,
108then the following environment variables are searched: \envvar{LANGUAGE},
109\envvar{LC_ALL}, \envvar{LC_MESSAGES}, and \envvar{LANG}. The first one
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000110returning a non-empty value is used for the \var{languages} variable.
Barry Warsaw91b81c42001-10-18 19:41:48 +0000111The environment variables should contain a colon separated list of
112languages, which will be split on the colon to produce the expected
113list of language code strings.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000114
115\function{find()} then expands and normalizes the languages, and then
116iterates through them, searching for an existing file built of these
117components:
118
119\file{\var{localedir}/\var{language}/LC_MESSAGES/\var{domain}.mo}
120
121The first such file name that exists is returned by \function{find()}.
122If no such file is found, then \code{None} is returned.
123\end{funcdesc}
124
Fred Draked576e9d2000-08-30 04:19:20 +0000125\begin{funcdesc}{translation}{domain\optional{, localedir\optional{,
126 languages\optional{, class_}}}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000127Return a \class{Translations} instance based on the \var{domain},
128\var{localedir}, and \var{languages}, which are first passed to
129\function{find()} to get the
130associated \file{.mo} file path. Instances with
131identical \file{.mo} file names are cached. The actual class instantiated
132is either \var{class_} if provided, otherwise
133\class{GNUTranslations}. The class's constructor must take a single
134file object argument. If no \file{.mo} file is found, this
135function raises \exception{IOError}.
136\end{funcdesc}
137
Fred Draked576e9d2000-08-30 04:19:20 +0000138\begin{funcdesc}{install}{domain\optional{, localedir\optional{, unicode}}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000139This installs the function \function{_} in Python's builtin namespace,
140based on \var{domain}, and \var{localedir} which are passed to the
141function \function{translation()}. The \var{unicode} flag is passed to
142the resulting translation object's \method{install} method.
143
144As seen below, you usually mark the strings in your application that are
Fred Drake91f2f262001-07-06 19:28:48 +0000145candidates for translation, by wrapping them in a call to the
146\function{_()} function, like this:
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000147
148\begin{verbatim}
149print _('This string will be translated.')
150\end{verbatim}
151
152For convenience, you want the \function{_()} function to be installed in
153Python's builtin namespace, so it is easily accessible in all modules
154of your application.
155\end{funcdesc}
156
157\subsubsection{The \class{NullTranslations} class}
158Translation classes are what actually implement the translation of
159original source file message strings to translated message strings.
160The base class used by all translation classes is
161\class{NullTranslations}; this provides the basic interface you can use
162to write your own specialized translation classes. Here are the
163methods of \class{NullTranslations}:
164
Fred Draked576e9d2000-08-30 04:19:20 +0000165\begin{methoddesc}[NullTranslations]{__init__}{\optional{fp}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000166Takes an optional file object \var{fp}, which is ignored by the base
167class. Initializes ``protected'' instance variables \var{_info} and
168\var{_charset} which are set by derived classes. It then calls
169\code{self._parse(fp)} if \var{fp} is not \code{None}.
170\end{methoddesc}
171
172\begin{methoddesc}[NullTranslations]{_parse}{fp}
173No-op'd in the base class, this method takes file object \var{fp}, and
174reads the data from the file, initializing its message catalog. If
175you have an unsupported message catalog file format, you should
176override this method to parse your format.
177\end{methoddesc}
178
179\begin{methoddesc}[NullTranslations]{gettext}{message}
180Return the translated message. Overridden in derived classes.
181\end{methoddesc}
182
183\begin{methoddesc}[NullTranslations]{ugettext}{message}
184Return the translated message as a Unicode string. Overridden in
185derived classes.
186\end{methoddesc}
187
188\begin{methoddesc}[NullTranslations]{info}{}
Fred Draked576e9d2000-08-30 04:19:20 +0000189Return the ``protected'' \member{_info} variable.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000190\end{methoddesc}
191
192\begin{methoddesc}[NullTranslations]{charset}{}
Fred Draked576e9d2000-08-30 04:19:20 +0000193Return the ``protected'' \member{_charset} variable.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000194\end{methoddesc}
195
Fred Draked576e9d2000-08-30 04:19:20 +0000196\begin{methoddesc}[NullTranslations]{install}{\optional{unicode}}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000197If the \var{unicode} flag is false, this method installs
Fred Draked576e9d2000-08-30 04:19:20 +0000198\method{self.gettext()} into the built-in namespace, binding it to
199\samp{_}. If \var{unicode} is true, it binds \method{self.ugettext()}
200instead. By default, \var{unicode} is false.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000201
202Note that this is only one way, albeit the most convenient way, to
203make the \function{_} function available to your application. Because it
204affects the entire application globally, and specifically the built-in
205namespace, localized modules should never install \function{_}.
206Instead, they should use this code to make \function{_} available to
207their module:
208
209\begin{verbatim}
210import gettext
211t = gettext.translation('mymodule', ...)
212_ = t.gettext
213\end{verbatim}
214
215This puts \function{_} only in the module's global namespace and so
216only affects calls within this module.
217\end{methoddesc}
218
219\subsubsection{The \class{GNUTranslations} class}
220
221The \module{gettext} module provides one additional class derived from
222\class{NullTranslations}: \class{GNUTranslations}. This class
223overrides \method{_parse()} to enable reading GNU \program{gettext}
224format \file{.mo} files in both big-endian and little-endian format.
225
226It also parses optional meta-data out of the translation catalog. It
227is convention with GNU \program{gettext} to include meta-data as the
Fred Draked576e9d2000-08-30 04:19:20 +0000228translation for the empty string. This meta-data is in \rfc{822}-style
229\code{key: value} pairs. If the key \code{Content-Type} is found,
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000230then the \code{charset} property is used to initialize the
Fred Draked576e9d2000-08-30 04:19:20 +0000231``protected'' \member{_charset} instance variable. The entire set of
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000232key/value pairs are placed into a dictionary and set as the
Fred Draked576e9d2000-08-30 04:19:20 +0000233``protected'' \member{_info} instance variable.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000234
235If the \file{.mo} file's magic number is invalid, or if other problems
236occur while reading the file, instantiating a \class{GNUTranslations} class
237can raise \exception{IOError}.
238
239The other usefully overridden method is \method{ugettext()}, which
240returns a Unicode string by passing both the translated message string
Fred Draked576e9d2000-08-30 04:19:20 +0000241and the value of the ``protected'' \member{_charset} variable to the
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000242builtin \function{unicode()} function.
243
Fred Draked0726c32000-09-07 18:55:08 +0000244\subsubsection{Solaris message catalog support}
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000245
246The Solaris operating system defines its own binary
247\file{.mo} file format, but since no documentation can be found on
248this format, it is not supported at this time.
249
250\subsubsection{The Catalog constructor}
251
Fred Draked0726c32000-09-07 18:55:08 +0000252GNOME\index{GNOME} uses a version of the \module{gettext} module by
253James Henstridge, but this version has a slightly different API. Its
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000254documented usage was:
255
256\begin{verbatim}
257import gettext
258cat = gettext.Catalog(domain, localedir)
259_ = cat.gettext
260print _('hello world')
261\end{verbatim}
262
263For compatibility with this older module, the function
264\function{Catalog()} is an alias for the the \function{translation()}
265function described above.
266
267One difference between this module and Henstridge's: his catalog
268objects supported access through a mapping API, but this appears to be
269unused and so is not currently supported.
270
271\subsection{Internationalizing your programs and modules}
272Internationalization (I18N) refers to the operation by which a program
273is made aware of multiple languages. Localization (L10N) refers to
274the adaptation of your program, once internationalized, to the local
275language and cultural habits. In order to provide multilingual
276messages for your Python programs, you need to take the following
277steps:
278
279\begin{enumerate}
280 \item prepare your program or module by specially marking
281 translatable strings
282 \item run a suite of tools over your marked files to generate raw
283 messages catalogs
284 \item create language specific translations of the message catalogs
285 \item use the \module{gettext} module so that message strings are
286 properly translated
287\end{enumerate}
288
289In order to prepare your code for I18N, you need to look at all the
290strings in your files. Any string that needs to be translated
Fred Drake91f2f262001-07-06 19:28:48 +0000291should be marked by wrapping it in \code{_('...')} --- that is, a call
292to the function \function{_()}. For example:
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000293
294\begin{verbatim}
295filename = 'mylog.txt'
296message = _('writing a log message')
297fp = open(filename, 'w')
298fp.write(message)
299fp.close()
300\end{verbatim}
301
Fred Draked576e9d2000-08-30 04:19:20 +0000302In this example, the string \code{'writing a log message'} is marked as
303a candidate for translation, while the strings \code{'mylog.txt'} and
304\code{'w'} are not.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000305
Barry Warsawb4162902001-01-31 21:21:45 +0000306The Python distribution comes with two tools which help you generate
307the message catalogs once you've prepared your source code. These may
308or may not be available from a binary distribution, but they can be
309found in a source distribution, in the \file{Tools/i18n} directory.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000310
Barry Warsawb4162902001-01-31 21:21:45 +0000311The \program{pygettext}\footnote{Fran\c cois Pinard has
312written a program called
Barry Warsawddef8882000-09-13 12:04:47 +0000313\program{xpot} which does a similar job. It is available as part of
314his \program{po-utils} package at
Barry Warsawb4162902001-01-31 21:21:45 +0000315\url{http://www.iro.umontreal.ca/contrib/po-utils/HTML}.} program
316scans all your Python source code looking for the strings you
317previously marked as translatable. It is similar to the GNU
318\program{gettext} program except that it understands all the
319intricacies of Python source code, but knows nothing about C or C++
320source code. You don't need GNU \code{gettext} unless you're also
Fred Drake91f2f262001-07-06 19:28:48 +0000321going to be translating C code (such as C extension modules).
Barry Warsawb4162902001-01-31 21:21:45 +0000322
323\program{pygettext} generates textual Uniforum-style human readable
324message catalog \file{.pot} files, essentially structured human
325readable files which contain every marked string in the source code,
326along with a placeholder for the translation strings.
327\program{pygettext} is a command line script that supports a similar
328command line interface as \program{xgettext}; for details on its use,
329run:
330
331\begin{verbatim}
332pygettext.py --help
333\end{verbatim}
334
335Copies of these \file{.pot} files are then handed over to the
336individual human translators who write language-specific versions for
337every supported natural language. They send you back the filled in
338language-specific versions as a \file{.po} file. Using the
339\program{msgfmt.py}\footnote{\program{msgfmt.py} is binary
340compatible with GNU \program{msgfmt} except that it provides a
341simpler, all-Python implementation. With this and
342\program{pygettext.py}, you generally won't need to install the GNU
343\program{gettext} package to internationalize your Python
344applications.} program (in the \file{Tools/i18n} directory), you take the
345\file{.po} files from your translators and generate the
346machine-readable \file{.mo} binary catalog files. The \file{.mo}
347files are what the \module{gettext} module uses for the actual
348translation processing during run-time.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000349
350How you use the \module{gettext} module in your code depends on
351whether you are internationalizing your entire application or a single
352module.
353
354\subsubsection{Localizing your module}
355
356If you are localizing your module, you must take care not to make
357global changes, e.g. to the built-in namespace. You should not use
Fred Draked576e9d2000-08-30 04:19:20 +0000358the GNU \code{gettext} API but instead the class-based API.
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000359
360Let's say your module is called ``spam'' and the module's various
361natural language translation \file{.mo} files reside in
Fred Draked576e9d2000-08-30 04:19:20 +0000362\file{/usr/share/locale} in GNU \program{gettext} format. Here's what
363you would put at the top of your module:
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000364
365\begin{verbatim}
366import gettext
367t = gettext.translation('spam', '/usr/share/locale')
368_ = t.gettext
369\end{verbatim}
370
371If your translators were providing you with Unicode strings in their
372\file{.po} files, you'd instead do:
373
374\begin{verbatim}
375import gettext
376t = gettext.translation('spam', '/usr/share/locale')
377_ = t.ugettext
378\end{verbatim}
379
380\subsubsection{Localizing your application}
381
382If you are localizing your application, you can install the \function{_()}
383function globally into the built-in namespace, usually in the main driver file
384of your application. This will let all your application-specific
385files just use \code{_('...')} without having to explicitly install it in
386each file.
387
388In the simple case then, you need only add the following bit of code
389to the main driver file of your application:
390
391\begin{verbatim}
392import gettext
393gettext.install('myapplication')
394\end{verbatim}
395
Fred Draked576e9d2000-08-30 04:19:20 +0000396If you need to set the locale directory or the \var{unicode} flag,
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000397you can pass these into the \function{install()} function:
398
399\begin{verbatim}
400import gettext
401gettext.install('myapplication', '/usr/share/locale', unicode=1)
402\end{verbatim}
403
404\subsubsection{Changing languages on the fly}
405
406If your program needs to support many languages at the same time, you
407may want to create multiple translation instances and then switch
408between them explicitly, like so:
409
410\begin{verbatim}
411import gettext
412
413lang1 = gettext.translation(languages=['en'])
414lang2 = gettext.translation(languages=['fr'])
415lang3 = gettext.translation(languages=['de'])
416
417# start by using language1
418lang1.install()
419
420# ... time goes by, user selects language 2
421lang2.install()
422
423# ... more time goes by, user selects language 3
424lang3.install()
425\end{verbatim}
426
427\subsubsection{Deferred translations}
428
429In most coding situations, strings are translated were they are coded.
430Occasionally however, you need to mark strings for translation, but
431defer actual translation until later. A classic example is:
432
433\begin{verbatim}
434animals = ['mollusk',
435 'albatross',
436 'rat',
437 'penguin',
438 'python',
439 ]
440# ...
441for a in animals:
442 print a
443\end{verbatim}
444
445Here, you want to mark the strings in the \code{animals} list as being
446translatable, but you don't actually want to translate them until they
447are printed.
448
449Here is one way you can handle this situation:
450
451\begin{verbatim}
452def _(message): return message
453
454animals = [_('mollusk'),
455 _('albatross'),
456 _('rat'),
457 _('penguin'),
458 _('python'),
459 ]
460
461del _
462
463# ...
464for a in animals:
465 print _(a)
466\end{verbatim}
467
468This works because the dummy definition of \function{_()} simply returns
469the string unchanged. And this dummy definition will temporarily
470override any definition of \function{_()} in the built-in namespace
Fred Draked576e9d2000-08-30 04:19:20 +0000471(until the \keyword{del} command).
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000472Take care, though if you have a previous definition of \function{_} in
473the local namespace.
474
475Note that the second use of \function{_()} will not identify ``a'' as
476being translatable to the \program{pygettext} program, since it is not
477a string.
478
479Another way to handle this is with the following example:
480
481\begin{verbatim}
482def N_(message): return message
483
484animals = [N_('mollusk'),
485 N_('albatross'),
486 N_('rat'),
487 N_('penguin'),
488 N_('python'),
489 ]
490
491# ...
492for a in animals:
493 print _(a)
494\end{verbatim}
495
496In this case, you are marking translatable strings with the function
Fred Draked576e9d2000-08-30 04:19:20 +0000497\function{N_()},\footnote{The choice of \function{N_()} here is totally
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000498arbitrary; it could have just as easily been
Fred Draked576e9d2000-08-30 04:19:20 +0000499\function{MarkThisStringForTranslation()}.
500} which won't conflict with any definition of
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000501\function{_()}. However, you will need to teach your message extraction
502program to look for translatable strings marked with \function{N_()}.
503\program{pygettext} and \program{xpot} both support this through the
504use of command line switches.
505
506\subsection{Acknowledgements}
507
508The following people contributed code, feedback, design suggestions,
509previous implementations, and valuable experience to the creation of
510this module:
511
512\begin{itemize}
513 \item Peter Funk
514 \item James Henstridge
Fred Draked576e9d2000-08-30 04:19:20 +0000515 \item Marc-Andr\'e Lemburg
Barry Warsaw0691a6b2000-08-30 03:27:10 +0000516 \item Martin von L\"owis
517 \item Fran\c cois Pinard
518 \item Barry Warsaw
519\end{itemize}