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