Bump version to 1.0.
[python/dscho.git] / Doc / lib / libgettext.tex
blob8c9886fb9c2bc1c20e83a964f80c586d20f534fb
1 \section{\module{gettext} ---
2 Multilingual internationalization services}
4 \declaremodule{standard}{gettext}
5 \modulesynopsis{Multilingual internationalization services.}
6 \moduleauthor{Barry A. Warsaw}{bwarsaw@beopen.com}
7 \sectionauthor{Barry A. Warsaw}{bwarsaw@beopen.com}
10 The \module{gettext} module provides internationalization (I18N) and
11 localization (L10N) services for your Python modules and applications.
12 It supports both the GNU \code{gettext} message catalog API and a
13 higher level, class-based API that may be more appropriate for Python
14 files. The interface described below allows you to write your
15 module and application messages in one natural language, and provide a
16 catalog of translated messages for running under different natural
17 languages.
19 Some hints on localizing your Python modules and applications are also
20 given.
22 \subsection{GNU \program{gettext} API}
24 The \module{gettext} module defines the following API, which is very
25 similar to the GNU \program{gettext} API. If you use this API you
26 will affect the translation of your entire application globally. Often
27 this is what you want if your application is monolingual, with the choice
28 of language dependent on the locale of your user. If you are
29 localizing a Python module, or if your application needs to switch
30 languages on the fly, you probably want to use the class-based API
31 instead.
33 \begin{funcdesc}{bindtextdomain}{domain\optional{, localedir}}
34 Bind the \var{domain} to the locale directory
35 \var{localedir}. More concretely, \module{gettext} will look for
36 binary \file{.mo} files for the given domain using the path (on \UNIX):
37 \file{\var{localedir}/\var{language}/LC_MESSAGES/\var{domain}.mo},
38 where \var{languages} is searched for in the environment variables
39 \envvar{LANGUAGE}, \envvar{LC_ALL}, \envvar{LC_MESSAGES}, and
40 \envvar{LANG} respectively.
42 If \var{localedir} is omitted or \code{None}, then the current binding
43 for \var{domain} is returned.\footnote{
44 The default locale directory is system dependent; e.g.\ on
45 RedHat Linux it is \file{/usr/share/locale}, but on Solaris it
46 is \file{/usr/lib/locale}. The \module{gettext} module does
47 not try to support these system dependent defaults; instead
48 its default is \file{\code{sys.prefix}/share/locale}. For
49 this reason, it is always best to call
50 \function{bindtextdomain()} with an explicit absolute path at
51 the start of your application.}
52 \end{funcdesc}
54 \begin{funcdesc}{textdomain}{\optional{domain}}
55 Change or query the current global domain. If \var{domain} is
56 \code{None}, then the current global domain is returned, otherwise the
57 global domain is set to \var{domain}, which is returned.
58 \end{funcdesc}
60 \begin{funcdesc}{gettext}{message}
61 Return the localized translation of \var{message}, based on the
62 current global domain, language, and locale directory. This function
63 is usually aliased as \function{_} in the local namespace (see
64 examples below).
65 \end{funcdesc}
67 \begin{funcdesc}{dgettext}{domain, message}
68 Like \function{gettext()}, but look the message up in the specified
69 \var{domain}.
70 \end{funcdesc}
72 Note that GNU \program{gettext} also defines a \function{dcgettext()}
73 method, but this was deemed not useful and so it is currently
74 unimplemented.
76 Here's an example of typical usage for this API:
78 \begin{verbatim}
79 import gettext
80 gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
81 gettext.textdomain('myapplication')
82 _ = gettext.gettext
83 # ...
84 print _('This is a translatable string.')
85 \end{verbatim}
87 \subsection{Class-based API}
89 The class-based API of the \module{gettext} module gives you more
90 flexibility and greater convenience than the GNU \program{gettext}
91 API. It is the recommended way of localizing your Python applications and
92 modules. \module{gettext} defines a ``translations'' class which
93 implements the parsing of GNU \file{.mo} format files, and has methods
94 for returning either standard 8-bit strings or Unicode strings.
95 Translations instances can also install themselves in the built-in
96 namespace as the function \function{_()}.
98 \begin{funcdesc}{find}{domain\optional{, localedir\optional{, languages}}}
99 This function implements the standard \file{.mo} file search
100 algorithm. 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
103 are strings.
105 If \var{localedir} is not given, then the default system locale
106 directory is used.\footnote{See the footnote for
107 \function{bindtextdomain()} above.} If \var{languages} is not given,
108 then the following environment variables are searched: \envvar{LANGUAGE},
109 \envvar{LC_ALL}, \envvar{LC_MESSAGES}, and \envvar{LANG}. The first one
110 returning a non-empty value is used for the \var{languages} variable.
111 The environment variables can contain a colon separated list of
112 languages, which will be split.
114 \function{find()} then expands and normalizes the languages, and then
115 iterates through them, searching for an existing file built of these
116 components:
118 \file{\var{localedir}/\var{language}/LC_MESSAGES/\var{domain}.mo}
120 The first such file name that exists is returned by \function{find()}.
121 If no such file is found, then \code{None} is returned.
122 \end{funcdesc}
124 \begin{funcdesc}{translation}{domain\optional{, localedir\optional{,
125 languages\optional{, class_}}}}
126 Return 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
129 associated \file{.mo} file path. Instances with
130 identical \file{.mo} file names are cached. The actual class instantiated
131 is either \var{class_} if provided, otherwise
132 \class{GNUTranslations}. The class's constructor must take a single
133 file object argument. If no \file{.mo} file is found, this
134 function raises \exception{IOError}.
135 \end{funcdesc}
137 \begin{funcdesc}{install}{domain\optional{, localedir\optional{, unicode}}}
138 This installs the function \function{_} in Python's builtin namespace,
139 based on \var{domain}, and \var{localedir} which are passed to the
140 function \function{translation()}. The \var{unicode} flag is passed to
141 the resulting translation object's \method{install} method.
143 As seen below, you usually mark the strings in your application that are
144 candidates for translation, by wrapping them in a call to the function
145 \function{_()}, e.g.
147 \begin{verbatim}
148 print _('This string will be translated.')
149 \end{verbatim}
151 For convenience, you want the \function{_()} function to be installed in
152 Python's builtin namespace, so it is easily accessible in all modules
153 of your application.
154 \end{funcdesc}
156 \subsubsection{The \class{NullTranslations} class}
157 Translation classes are what actually implement the translation of
158 original source file message strings to translated message strings.
159 The base class used by all translation classes is
160 \class{NullTranslations}; this provides the basic interface you can use
161 to write your own specialized translation classes. Here are the
162 methods of \class{NullTranslations}:
164 \begin{methoddesc}[NullTranslations]{__init__}{\optional{fp}}
165 Takes an optional file object \var{fp}, which is ignored by the base
166 class. 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}
171 \begin{methoddesc}[NullTranslations]{_parse}{fp}
172 No-op'd in the base class, this method takes file object \var{fp}, and
173 reads the data from the file, initializing its message catalog. If
174 you have an unsupported message catalog file format, you should
175 override this method to parse your format.
176 \end{methoddesc}
178 \begin{methoddesc}[NullTranslations]{gettext}{message}
179 Return the translated message. Overridden in derived classes.
180 \end{methoddesc}
182 \begin{methoddesc}[NullTranslations]{ugettext}{message}
183 Return the translated message as a Unicode string. Overridden in
184 derived classes.
185 \end{methoddesc}
187 \begin{methoddesc}[NullTranslations]{info}{}
188 Return the ``protected'' \member{_info} variable.
189 \end{methoddesc}
191 \begin{methoddesc}[NullTranslations]{charset}{}
192 Return the ``protected'' \member{_charset} variable.
193 \end{methoddesc}
195 \begin{methoddesc}[NullTranslations]{install}{\optional{unicode}}
196 If the \var{unicode} flag is false, this method installs
197 \method{self.gettext()} into the built-in namespace, binding it to
198 \samp{_}. If \var{unicode} is true, it binds \method{self.ugettext()}
199 instead. By default, \var{unicode} is false.
201 Note that this is only one way, albeit the most convenient way, to
202 make the \function{_} function available to your application. Because it
203 affects the entire application globally, and specifically the built-in
204 namespace, localized modules should never install \function{_}.
205 Instead, they should use this code to make \function{_} available to
206 their module:
208 \begin{verbatim}
209 import gettext
210 t = gettext.translation('mymodule', ...)
211 _ = t.gettext
212 \end{verbatim}
214 This puts \function{_} only in the module's global namespace and so
215 only affects calls within this module.
216 \end{methoddesc}
218 \subsubsection{The \class{GNUTranslations} class}
220 The \module{gettext} module provides one additional class derived from
221 \class{NullTranslations}: \class{GNUTranslations}. This class
222 overrides \method{_parse()} to enable reading GNU \program{gettext}
223 format \file{.mo} files in both big-endian and little-endian format.
225 It also parses optional meta-data out of the translation catalog. It
226 is convention with GNU \program{gettext} to include meta-data as the
227 translation 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,
229 then the \code{charset} property is used to initialize the
230 ``protected'' \member{_charset} instance variable. The entire set of
231 key/value pairs are placed into a dictionary and set as the
232 ``protected'' \member{_info} instance variable.
234 If the \file{.mo} file's magic number is invalid, or if other problems
235 occur while reading the file, instantiating a \class{GNUTranslations} class
236 can raise \exception{IOError}.
238 The other usefully overridden method is \method{ugettext()}, which
239 returns a Unicode string by passing both the translated message string
240 and the value of the ``protected'' \member{_charset} variable to the
241 builtin \function{unicode()} function.
243 \subsubsection{Solaris message catalog support}
245 The Solaris operating system defines its own binary
246 \file{.mo} file format, but since no documentation can be found on
247 this format, it is not supported at this time.
249 \subsubsection{The Catalog constructor}
251 GNOME\index{GNOME} uses a version of the \module{gettext} module by
252 James Henstridge, but this version has a slightly different API. Its
253 documented usage was:
255 \begin{verbatim}
256 import gettext
257 cat = gettext.Catalog(domain, localedir)
258 _ = cat.gettext
259 print _('hello world')
260 \end{verbatim}
262 For compatibility with this older module, the function
263 \function{Catalog()} is an alias for the the \function{translation()}
264 function described above.
266 One difference between this module and Henstridge's: his catalog
267 objects supported access through a mapping API, but this appears to be
268 unused and so is not currently supported.
270 \subsection{Internationalizing your programs and modules}
271 Internationalization (I18N) refers to the operation by which a program
272 is made aware of multiple languages. Localization (L10N) refers to
273 the adaptation of your program, once internationalized, to the local
274 language and cultural habits. In order to provide multilingual
275 messages for your Python programs, you need to take the following
276 steps:
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}
288 In order to prepare your code for I18N, you need to look at all the
289 strings in your files. Any string that needs to be translated
290 should be marked by wrapping it in \code{_('...')} -- i.e. a call to
291 the function \function{_()}. For example:
293 \begin{verbatim}
294 filename = 'mylog.txt'
295 message = _('writing a log message')
296 fp = open(filename, 'w')
297 fp.write(message)
298 fp.close()
299 \end{verbatim}
301 In this example, the string \code{'writing a log message'} is marked as
302 a candidate for translation, while the strings \code{'mylog.txt'} and
303 \code{'w'} are not.
305 The GNU \code{gettext} package provides a tool, called
306 \program{xgettext}, that scans C and \Cpp{} source code looking for these
307 specially marked strings. \program{xgettext} generates what are
308 called \file{.pot} files, essentially structured human readable files
309 which contain every marked string in the source code. These
310 \file{.pot} files are copied and handed over to human translators who write
311 language-specific versions for every supported natural language.
313 For I18N Python programs however, \program{xgettext} won't work; it
314 doesn't understand the myriad of string types support by Python. The
315 standard Python distribution provides a tool called
316 \program{pygettext} that does though (found in the \file{Tools/i18n/}
317 directory).\footnote{Fran\c cois Pinard has written a program called
318 \program{xpot} which does a similar job. It is available as part of
319 his \program{po-utils} package at
320 \url{http://www.iro.umontreal.ca/contrib/po-utils/HTML}.
321 } This is a command line script that
322 supports a similar interface as \program{xgettext}; see its
323 documentation for details. Once you've used \program{pygettext} to
324 create your \file{.pot} files, you can use the standard GNU
325 \program{gettext} tools to generate your machine-readable \file{.mo}
326 files, which are readable by the \class{GNUTranslations} class.
328 How you use the \module{gettext} module in your code depends on
329 whether you are internationalizing your entire application or a single
330 module.
332 \subsubsection{Localizing your module}
334 If you are localizing your module, you must take care not to make
335 global changes, e.g. to the built-in namespace. You should not use
336 the GNU \code{gettext} API but instead the class-based API.
338 Let's say your module is called ``spam'' and the module's various
339 natural language translation \file{.mo} files reside in
340 \file{/usr/share/locale} in GNU \program{gettext} format. Here's what
341 you would put at the top of your module:
343 \begin{verbatim}
344 import gettext
345 t = gettext.translation('spam', '/usr/share/locale')
346 _ = t.gettext
347 \end{verbatim}
349 If your translators were providing you with Unicode strings in their
350 \file{.po} files, you'd instead do:
352 \begin{verbatim}
353 import gettext
354 t = gettext.translation('spam', '/usr/share/locale')
355 _ = t.ugettext
356 \end{verbatim}
358 \subsubsection{Localizing your application}
360 If you are localizing your application, you can install the \function{_()}
361 function globally into the built-in namespace, usually in the main driver file
362 of your application. This will let all your application-specific
363 files just use \code{_('...')} without having to explicitly install it in
364 each file.
366 In the simple case then, you need only add the following bit of code
367 to the main driver file of your application:
369 \begin{verbatim}
370 import gettext
371 gettext.install('myapplication')
372 \end{verbatim}
374 If you need to set the locale directory or the \var{unicode} flag,
375 you can pass these into the \function{install()} function:
377 \begin{verbatim}
378 import gettext
379 gettext.install('myapplication', '/usr/share/locale', unicode=1)
380 \end{verbatim}
382 \subsubsection{Changing languages on the fly}
384 If your program needs to support many languages at the same time, you
385 may want to create multiple translation instances and then switch
386 between them explicitly, like so:
388 \begin{verbatim}
389 import gettext
391 lang1 = gettext.translation(languages=['en'])
392 lang2 = gettext.translation(languages=['fr'])
393 lang3 = gettext.translation(languages=['de'])
395 # start by using language1
396 lang1.install()
398 # ... time goes by, user selects language 2
399 lang2.install()
401 # ... more time goes by, user selects language 3
402 lang3.install()
403 \end{verbatim}
405 \subsubsection{Deferred translations}
407 In most coding situations, strings are translated were they are coded.
408 Occasionally however, you need to mark strings for translation, but
409 defer actual translation until later. A classic example is:
411 \begin{verbatim}
412 animals = ['mollusk',
413 'albatross',
414 'rat',
415 'penguin',
416 'python',
418 # ...
419 for a in animals:
420 print a
421 \end{verbatim}
423 Here, you want to mark the strings in the \code{animals} list as being
424 translatable, but you don't actually want to translate them until they
425 are printed.
427 Here is one way you can handle this situation:
429 \begin{verbatim}
430 def _(message): return message
432 animals = [_('mollusk'),
433 _('albatross'),
434 _('rat'),
435 _('penguin'),
436 _('python'),
439 del _
441 # ...
442 for a in animals:
443 print _(a)
444 \end{verbatim}
446 This works because the dummy definition of \function{_()} simply returns
447 the string unchanged. And this dummy definition will temporarily
448 override any definition of \function{_()} in the built-in namespace
449 (until the \keyword{del} command).
450 Take care, though if you have a previous definition of \function{_} in
451 the local namespace.
453 Note that the second use of \function{_()} will not identify ``a'' as
454 being translatable to the \program{pygettext} program, since it is not
455 a string.
457 Another way to handle this is with the following example:
459 \begin{verbatim}
460 def N_(message): return message
462 animals = [N_('mollusk'),
463 N_('albatross'),
464 N_('rat'),
465 N_('penguin'),
466 N_('python'),
469 # ...
470 for a in animals:
471 print _(a)
472 \end{verbatim}
474 In this case, you are marking translatable strings with the function
475 \function{N_()},\footnote{The choice of \function{N_()} here is totally
476 arbitrary; it could have just as easily been
477 \function{MarkThisStringForTranslation()}.
478 } which won't conflict with any definition of
479 \function{_()}. However, you will need to teach your message extraction
480 program to look for translatable strings marked with \function{N_()}.
481 \program{pygettext} and \program{xpot} both support this through the
482 use of command line switches.
484 \subsection{Acknowledgements}
486 The following people contributed code, feedback, design suggestions,
487 previous implementations, and valuable experience to the creation of
488 this module:
490 \begin{itemize}
491 \item Peter Funk
492 \item James Henstridge
493 \item Marc-Andr\'e Lemburg
494 \item Martin von L\"owis
495 \item Fran\c cois Pinard
496 \item Barry Warsaw
497 \end{itemize}