This commit was manufactured by cvs2svn to create tag 'r241c1'.
[python/dscho.git] / Doc / lib / libgettext.tex
blob593d964c8d1ba8e2773651f737d90d767db151a5
1 \section{\module{gettext} ---
2 Multilingual internationalization services}
4 \declaremodule{standard}{gettext}
5 \modulesynopsis{Multilingual internationalization services.}
6 \moduleauthor{Barry A. Warsaw}{barry@zope.com}
7 \sectionauthor{Barry A. Warsaw}{barry@zope.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; 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
50 \function{bindtextdomain()} with an explicit absolute path at
51 the start of your application.}
52 \end{funcdesc}
54 \begin{funcdesc}{bind_textdomain_codeset}{domain\optional{, codeset}}
55 Bind the \var{domain} to \var{codeset}, changing the encoding of
56 strings returned by the \function{gettext()} family of functions.
57 If \var{codeset} is omitted, then the current binding is returned.
59 \versionadded{2.4}
60 \end{funcdesc}
62 \begin{funcdesc}{textdomain}{\optional{domain}}
63 Change or query the current global domain. If \var{domain} is
64 \code{None}, then the current global domain is returned, otherwise the
65 global domain is set to \var{domain}, which is returned.
66 \end{funcdesc}
68 \begin{funcdesc}{gettext}{message}
69 Return the localized translation of \var{message}, based on the
70 current global domain, language, and locale directory. This function
71 is usually aliased as \function{_} in the local namespace (see
72 examples below).
73 \end{funcdesc}
75 \begin{funcdesc}{lgettext}{message}
76 Equivalent to \function{gettext()}, but the translation is returned
77 in the preferred system encoding, if no other encoding was explicitly
78 set with \function{bind_textdomain_codeset()}.
80 \versionadded{2.4}
81 \end{funcdesc}
83 \begin{funcdesc}{dgettext}{domain, message}
84 Like \function{gettext()}, but look the message up in the specified
85 \var{domain}.
86 \end{funcdesc}
88 \begin{funcdesc}{ldgettext}{domain, message}
89 Equivalent to \function{dgettext()}, but the translation is returned
90 in the preferred system encoding, if no other encoding was explicitly
91 set with \function{bind_textdomain_codeset()}.
93 \versionadded{2.4}
94 \end{funcdesc}
96 \begin{funcdesc}{ngettext}{singular, plural, n}
98 Like \function{gettext()}, but consider plural forms. If a translation
99 is found, apply the plural formula to \var{n}, and return the
100 resulting message (some languages have more than two plural forms).
101 If no translation is found, return \var{singular} if \var{n} is 1;
102 return \var{plural} otherwise.
104 The Plural formula is taken from the catalog header. It is a C or
105 Python expression that has a free variable n; the expression evaluates
106 to the index of the plural in the catalog. See the GNU gettext
107 documentation for the precise syntax to be used in .po files, and the
108 formulas for a variety of languages.
110 \versionadded{2.3}
112 \end{funcdesc}
114 \begin{funcdesc}{lngettext}{singular, plural, n}
115 Equivalent to \function{ngettext()}, but the translation is returned
116 in the preferred system encoding, if no other encoding was explicitly
117 set with \function{bind_textdomain_codeset()}.
119 \versionadded{2.4}
120 \end{funcdesc}
122 \begin{funcdesc}{dngettext}{domain, singular, plural, n}
123 Like \function{ngettext()}, but look the message up in the specified
124 \var{domain}.
126 \versionadded{2.3}
127 \end{funcdesc}
129 \begin{funcdesc}{ldngettext}{domain, singular, plural, n}
130 Equivalent to \function{dngettext()}, but the translation is returned
131 in the preferred system encoding, if no other encoding was explicitly
132 set with \function{bind_textdomain_codeset()}.
134 \versionadded{2.4}
135 \end{funcdesc}
139 Note that GNU \program{gettext} also defines a \function{dcgettext()}
140 method, but this was deemed not useful and so it is currently
141 unimplemented.
143 Here's an example of typical usage for this API:
145 \begin{verbatim}
146 import gettext
147 gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
148 gettext.textdomain('myapplication')
149 _ = gettext.gettext
150 # ...
151 print _('This is a translatable string.')
152 \end{verbatim}
154 \subsection{Class-based API}
156 The class-based API of the \module{gettext} module gives you more
157 flexibility and greater convenience than the GNU \program{gettext}
158 API. It is the recommended way of localizing your Python applications and
159 modules. \module{gettext} defines a ``translations'' class which
160 implements the parsing of GNU \file{.mo} format files, and has methods
161 for returning either standard 8-bit strings or Unicode strings.
162 Instances of this ``translations'' class can also install themselves
163 in the built-in namespace as the function \function{_()}.
165 \begin{funcdesc}{find}{domain\optional{, localedir\optional{,
166 languages\optional{, all}}}}
167 This function implements the standard \file{.mo} file search
168 algorithm. It takes a \var{domain}, identical to what
169 \function{textdomain()} takes. Optional \var{localedir} is as in
170 \function{bindtextdomain()} Optional \var{languages} is a list of
171 strings, where each string is a language code.
173 If \var{localedir} is not given, then the default system locale
174 directory is used.\footnote{See the footnote for
175 \function{bindtextdomain()} above.} If \var{languages} is not given,
176 then the following environment variables are searched: \envvar{LANGUAGE},
177 \envvar{LC_ALL}, \envvar{LC_MESSAGES}, and \envvar{LANG}. The first one
178 returning a non-empty value is used for the \var{languages} variable.
179 The environment variables should contain a colon separated list of
180 languages, which will be split on the colon to produce the expected
181 list of language code strings.
183 \function{find()} then expands and normalizes the languages, and then
184 iterates through them, searching for an existing file built of these
185 components:
187 \file{\var{localedir}/\var{language}/LC_MESSAGES/\var{domain}.mo}
189 The first such file name that exists is returned by \function{find()}.
190 If no such file is found, then \code{None} is returned. If \var{all}
191 is given, it returns a list of all file names, in the order in which
192 they appear in the languages list or the environment variables.
193 \end{funcdesc}
195 \begin{funcdesc}{translation}{domain\optional{, localedir\optional{,
196 languages\optional{, class_\optional{,
197 fallback\optional{, codeset}}}}}}
198 Return a \class{Translations} instance based on the \var{domain},
199 \var{localedir}, and \var{languages}, which are first passed to
200 \function{find()} to get a list of the
201 associated \file{.mo} file paths. Instances with
202 identical \file{.mo} file names are cached. The actual class instantiated
203 is either \var{class_} if provided, otherwise
204 \class{GNUTranslations}. The class's constructor must take a single
205 file object argument. If provided, \var{codeset} will change the
206 charset used to encode translated strings.
208 If multiple files are found, later files are used as fallbacks for
209 earlier ones. To allow setting the fallback, \function{copy.copy}
210 is used to clone each translation object from the cache; the actual
211 instance data is still shared with the cache.
213 If no \file{.mo} file is found, this function raises
214 \exception{IOError} if \var{fallback} is false (which is the default),
215 and returns a \class{NullTranslations} instance if \var{fallback} is
216 true.
218 \versionchanged[Added the \var{codeset} parameter]{2.4}
219 \end{funcdesc}
221 \begin{funcdesc}{install}{domain\optional{, localedir\optional{, unicode
222 \optional{, codeset}}}}
223 This installs the function \function{_} in Python's builtin namespace,
224 based on \var{domain}, \var{localedir}, and \var{codeset} which are
225 passed to the function \function{translation()}. The \var{unicode}
226 flag is passed to the resulting translation object's \method{install}
227 method.
229 As seen below, you usually mark the strings in your application that are
230 candidates for translation, by wrapping them in a call to the
231 \function{_()} function, like this:
233 \begin{verbatim}
234 print _('This string will be translated.')
235 \end{verbatim}
237 For convenience, you want the \function{_()} function to be installed in
238 Python's builtin namespace, so it is easily accessible in all modules
239 of your application.
241 \versionchanged[Added the \var{codeset} parameter]{2.4}
242 \end{funcdesc}
244 \subsubsection{The \class{NullTranslations} class}
245 Translation classes are what actually implement the translation of
246 original source file message strings to translated message strings.
247 The base class used by all translation classes is
248 \class{NullTranslations}; this provides the basic interface you can use
249 to write your own specialized translation classes. Here are the
250 methods of \class{NullTranslations}:
252 \begin{methoddesc}[NullTranslations]{__init__}{\optional{fp}}
253 Takes an optional file object \var{fp}, which is ignored by the base
254 class. Initializes ``protected'' instance variables \var{_info} and
255 \var{_charset} which are set by derived classes, as well as \var{_fallback},
256 which is set through \method{add_fallback}. It then calls
257 \code{self._parse(fp)} if \var{fp} is not \code{None}.
258 \end{methoddesc}
260 \begin{methoddesc}[NullTranslations]{_parse}{fp}
261 No-op'd in the base class, this method takes file object \var{fp}, and
262 reads the data from the file, initializing its message catalog. If
263 you have an unsupported message catalog file format, you should
264 override this method to parse your format.
265 \end{methoddesc}
267 \begin{methoddesc}[NullTranslations]{add_fallback}{fallback}
268 Add \var{fallback} as the fallback object for the current translation
269 object. A translation object should consult the fallback if it cannot
270 provide a translation for a given message.
271 \end{methoddesc}
273 \begin{methoddesc}[NullTranslations]{gettext}{message}
274 If a fallback has been set, forward \method{gettext()} to the fallback.
275 Otherwise, return the translated message. Overridden in derived classes.
276 \end{methoddesc}
278 \begin{methoddesc}[NullTranslations]{lgettext}{message}
279 If a fallback has been set, forward \method{lgettext()} to the fallback.
280 Otherwise, return the translated message. Overridden in derived classes.
282 \versionadded{2.4}
283 \end{methoddesc}
285 \begin{methoddesc}[NullTranslations]{ugettext}{message}
286 If a fallback has been set, forward \method{ugettext()} to the fallback.
287 Otherwise, return the translated message as a Unicode string.
288 Overridden in derived classes.
289 \end{methoddesc}
291 \begin{methoddesc}[NullTranslations]{ngettext}{singular, plural, n}
292 If a fallback has been set, forward \method{ngettext()} to the fallback.
293 Otherwise, return the translated message. Overridden in derived classes.
295 \versionadded{2.3}
296 \end{methoddesc}
298 \begin{methoddesc}[NullTranslations]{lngettext}{singular, plural, n}
299 If a fallback has been set, forward \method{ngettext()} to the fallback.
300 Otherwise, return the translated message. Overridden in derived classes.
302 \versionadded{2.4}
303 \end{methoddesc}
305 \begin{methoddesc}[NullTranslations]{ungettext}{singular, plural, n}
306 If a fallback has been set, forward \method{ungettext()} to the fallback.
307 Otherwise, return the translated message as a Unicode string.
308 Overridden in derived classes.
310 \versionadded{2.3}
311 \end{methoddesc}
313 \begin{methoddesc}[NullTranslations]{info}{}
314 Return the ``protected'' \member{_info} variable.
315 \end{methoddesc}
317 \begin{methoddesc}[NullTranslations]{charset}{}
318 Return the ``protected'' \member{_charset} variable.
319 \end{methoddesc}
321 \begin{methoddesc}[NullTranslations]{output_charset}{}
322 Return the ``protected'' \member{_output_charset} variable, which
323 defines the encoding used to return translated messages.
325 \versionadded{2.4}
326 \end{methoddesc}
328 \begin{methoddesc}[NullTranslations]{set_output_charset}{charset}
329 Change the ``protected'' \member{_output_charset} variable, which
330 defines the encoding used to return translated messages.
332 \versionadded{2.4}
333 \end{methoddesc}
335 \begin{methoddesc}[NullTranslations]{install}{\optional{unicode}}
336 If the \var{unicode} flag is false, this method installs
337 \method{self.gettext()} into the built-in namespace, binding it to
338 \samp{_}. If \var{unicode} is true, it binds \method{self.ugettext()}
339 instead. By default, \var{unicode} is false.
341 Note that this is only one way, albeit the most convenient way, to
342 make the \function{_} function available to your application. Because it
343 affects the entire application globally, and specifically the built-in
344 namespace, localized modules should never install \function{_}.
345 Instead, they should use this code to make \function{_} available to
346 their module:
348 \begin{verbatim}
349 import gettext
350 t = gettext.translation('mymodule', ...)
351 _ = t.gettext
352 \end{verbatim}
354 This puts \function{_} only in the module's global namespace and so
355 only affects calls within this module.
356 \end{methoddesc}
358 \subsubsection{The \class{GNUTranslations} class}
360 The \module{gettext} module provides one additional class derived from
361 \class{NullTranslations}: \class{GNUTranslations}. This class
362 overrides \method{_parse()} to enable reading GNU \program{gettext}
363 format \file{.mo} files in both big-endian and little-endian format.
364 It also coerces both message ids and message strings to Unicode.
366 \class{GNUTranslations} parses optional meta-data out of the
367 translation catalog. It is convention with GNU \program{gettext} to
368 include meta-data as the translation for the empty string. This
369 meta-data is in \rfc{822}-style \code{key: value} pairs, and should
370 contain the \code{Project-Id-Version} key. If the key
371 \code{Content-Type} is found, then the \code{charset} property is used
372 to initialize the ``protected'' \member{_charset} instance variable,
373 defaulting to \code{None} if not found. If the charset encoding is
374 specified, then all message ids and message strings read from the
375 catalog are converted to Unicode using this encoding. The
376 \method{ugettext()} method always returns a Unicode, while the
377 \method{gettext()} returns an encoded 8-bit string. For the message
378 id arguments of both methods, either Unicode strings or 8-bit strings
379 containing only US-ASCII characters are acceptable. Note that the
380 Unicode version of the methods (i.e. \method{ugettext()} and
381 \method{ungettext()}) are the recommended interface to use for
382 internationalized Python programs.
384 The entire set of key/value pairs are placed into a dictionary and set
385 as the ``protected'' \member{_info} instance variable.
387 If the \file{.mo} file's magic number is invalid, or if other problems
388 occur while reading the file, instantiating a \class{GNUTranslations} class
389 can raise \exception{IOError}.
391 The following methods are overridden from the base class implementation:
393 \begin{methoddesc}[GNUTranslations]{gettext}{message}
394 Look up the \var{message} id in the catalog and return the
395 corresponding message string, as an 8-bit string encoded with the
396 catalog's charset encoding, if known. If there is no entry in the
397 catalog for the \var{message} id, and a fallback has been set, the
398 look up is forwarded to the fallback's \method{gettext()} method.
399 Otherwise, the \var{message} id is returned.
400 \end{methoddesc}
402 \begin{methoddesc}[GNUTranslations]{lgettext}{message}
403 Equivalent to \method{gettext()}, but the translation is returned
404 in the preferred system encoding, if no other encoding was explicitly
405 set with \method{set_output_charset()}.
407 \versionadded{2.4}
408 \end{methoddesc}
410 \begin{methoddesc}[GNUTranslations]{ugettext}{message}
411 Look up the \var{message} id in the catalog and return the
412 corresponding message string, as a Unicode string. If there is no
413 entry in the catalog for the \var{message} id, and a fallback has been
414 set, the look up is forwarded to the fallback's \method{ugettext()}
415 method. Otherwise, the \var{message} id is returned.
416 \end{methoddesc}
418 \begin{methoddesc}[GNUTranslations]{ngettext}{singular, plural, n}
419 Do a plural-forms lookup of a message id. \var{singular} is used as
420 the message id for purposes of lookup in the catalog, while \var{n} is
421 used to determine which plural form to use. The returned message
422 string is an 8-bit string encoded with the catalog's charset encoding,
423 if known.
425 If the message id is not found in the catalog, and a fallback is
426 specified, the request is forwarded to the fallback's
427 \method{ngettext()} method. Otherwise, when \var{n} is 1 \var{singular} is
428 returned, and \var{plural} is returned in all other cases.
430 \versionadded{2.3}
431 \end{methoddesc}
433 \begin{methoddesc}[GNUTranslations]{lngettext}{singular, plural, n}
434 Equivalent to \method{gettext()}, but the translation is returned
435 in the preferred system encoding, if no other encoding was explicitly
436 set with \method{set_output_charset()}.
438 \versionadded{2.4}
439 \end{methoddesc}
441 \begin{methoddesc}[GNUTranslations]{ungettext}{singular, plural, n}
442 Do a plural-forms lookup of a message id. \var{singular} is used as
443 the message id for purposes of lookup in the catalog, while \var{n} is
444 used to determine which plural form to use. The returned message
445 string is a Unicode string.
447 If the message id is not found in the catalog, and a fallback is
448 specified, the request is forwarded to the fallback's
449 \method{ungettext()} method. Otherwise, when \var{n} is 1 \var{singular} is
450 returned, and \var{plural} is returned in all other cases.
452 Here is an example:
454 \begin{verbatim}
455 n = len(os.listdir('.'))
456 cat = GNUTranslations(somefile)
457 message = cat.ungettext(
458 'There is %(num)d file in this directory',
459 'There are %(num)d files in this directory',
460 n) % {'num': n}
461 \end{verbatim}
463 \versionadded{2.3}
464 \end{methoddesc}
466 \subsubsection{Solaris message catalog support}
468 The Solaris operating system defines its own binary
469 \file{.mo} file format, but since no documentation can be found on
470 this format, it is not supported at this time.
472 \subsubsection{The Catalog constructor}
474 GNOME\index{GNOME} uses a version of the \module{gettext} module by
475 James Henstridge, but this version has a slightly different API. Its
476 documented usage was:
478 \begin{verbatim}
479 import gettext
480 cat = gettext.Catalog(domain, localedir)
481 _ = cat.gettext
482 print _('hello world')
483 \end{verbatim}
485 For compatibility with this older module, the function
486 \function{Catalog()} is an alias for the \function{translation()}
487 function described above.
489 One difference between this module and Henstridge's: his catalog
490 objects supported access through a mapping API, but this appears to be
491 unused and so is not currently supported.
493 \subsection{Internationalizing your programs and modules}
494 Internationalization (I18N) refers to the operation by which a program
495 is made aware of multiple languages. Localization (L10N) refers to
496 the adaptation of your program, once internationalized, to the local
497 language and cultural habits. In order to provide multilingual
498 messages for your Python programs, you need to take the following
499 steps:
501 \begin{enumerate}
502 \item prepare your program or module by specially marking
503 translatable strings
504 \item run a suite of tools over your marked files to generate raw
505 messages catalogs
506 \item create language specific translations of the message catalogs
507 \item use the \module{gettext} module so that message strings are
508 properly translated
509 \end{enumerate}
511 In order to prepare your code for I18N, you need to look at all the
512 strings in your files. Any string that needs to be translated
513 should be marked by wrapping it in \code{_('...')} --- that is, a call
514 to the function \function{_()}. For example:
516 \begin{verbatim}
517 filename = 'mylog.txt'
518 message = _('writing a log message')
519 fp = open(filename, 'w')
520 fp.write(message)
521 fp.close()
522 \end{verbatim}
524 In this example, the string \code{'writing a log message'} is marked as
525 a candidate for translation, while the strings \code{'mylog.txt'} and
526 \code{'w'} are not.
528 The Python distribution comes with two tools which help you generate
529 the message catalogs once you've prepared your source code. These may
530 or may not be available from a binary distribution, but they can be
531 found in a source distribution, in the \file{Tools/i18n} directory.
533 The \program{pygettext}\footnote{Fran\c cois Pinard has
534 written a program called
535 \program{xpot} which does a similar job. It is available as part of
536 his \program{po-utils} package at
537 \url{http://www.iro.umontreal.ca/contrib/po-utils/HTML/}.} program
538 scans all your Python source code looking for the strings you
539 previously marked as translatable. It is similar to the GNU
540 \program{gettext} program except that it understands all the
541 intricacies of Python source code, but knows nothing about C or \Cpp
542 source code. You don't need GNU \code{gettext} unless you're also
543 going to be translating C code (such as C extension modules).
545 \program{pygettext} generates textual Uniforum-style human readable
546 message catalog \file{.pot} files, essentially structured human
547 readable files which contain every marked string in the source code,
548 along with a placeholder for the translation strings.
549 \program{pygettext} is a command line script that supports a similar
550 command line interface as \program{xgettext}; for details on its use,
551 run:
553 \begin{verbatim}
554 pygettext.py --help
555 \end{verbatim}
557 Copies of these \file{.pot} files are then handed over to the
558 individual human translators who write language-specific versions for
559 every supported natural language. They send you back the filled in
560 language-specific versions as a \file{.po} file. Using the
561 \program{msgfmt.py}\footnote{\program{msgfmt.py} is binary
562 compatible with GNU \program{msgfmt} except that it provides a
563 simpler, all-Python implementation. With this and
564 \program{pygettext.py}, you generally won't need to install the GNU
565 \program{gettext} package to internationalize your Python
566 applications.} program (in the \file{Tools/i18n} directory), you take the
567 \file{.po} files from your translators and generate the
568 machine-readable \file{.mo} binary catalog files. The \file{.mo}
569 files are what the \module{gettext} module uses for the actual
570 translation processing during run-time.
572 How you use the \module{gettext} module in your code depends on
573 whether you are internationalizing your entire application or a single
574 module.
576 \subsubsection{Localizing your module}
578 If you are localizing your module, you must take care not to make
579 global changes, e.g. to the built-in namespace. You should not use
580 the GNU \code{gettext} API but instead the class-based API.
582 Let's say your module is called ``spam'' and the module's various
583 natural language translation \file{.mo} files reside in
584 \file{/usr/share/locale} in GNU \program{gettext} format. Here's what
585 you would put at the top of your module:
587 \begin{verbatim}
588 import gettext
589 t = gettext.translation('spam', '/usr/share/locale')
590 _ = t.lgettext
591 \end{verbatim}
593 If your translators were providing you with Unicode strings in their
594 \file{.po} files, you'd instead do:
596 \begin{verbatim}
597 import gettext
598 t = gettext.translation('spam', '/usr/share/locale')
599 _ = t.ugettext
600 \end{verbatim}
602 \subsubsection{Localizing your application}
604 If you are localizing your application, you can install the \function{_()}
605 function globally into the built-in namespace, usually in the main driver file
606 of your application. This will let all your application-specific
607 files just use \code{_('...')} without having to explicitly install it in
608 each file.
610 In the simple case then, you need only add the following bit of code
611 to the main driver file of your application:
613 \begin{verbatim}
614 import gettext
615 gettext.install('myapplication')
616 \end{verbatim}
618 If you need to set the locale directory or the \var{unicode} flag,
619 you can pass these into the \function{install()} function:
621 \begin{verbatim}
622 import gettext
623 gettext.install('myapplication', '/usr/share/locale', unicode=1)
624 \end{verbatim}
626 \subsubsection{Changing languages on the fly}
628 If your program needs to support many languages at the same time, you
629 may want to create multiple translation instances and then switch
630 between them explicitly, like so:
632 \begin{verbatim}
633 import gettext
635 lang1 = gettext.translation('myapplication', languages=['en'])
636 lang2 = gettext.translation('myapplication', languages=['fr'])
637 lang3 = gettext.translation('myapplication', languages=['de'])
639 # start by using language1
640 lang1.install()
642 # ... time goes by, user selects language 2
643 lang2.install()
645 # ... more time goes by, user selects language 3
646 lang3.install()
647 \end{verbatim}
649 \subsubsection{Deferred translations}
651 In most coding situations, strings are translated where they are coded.
652 Occasionally however, you need to mark strings for translation, but
653 defer actual translation until later. A classic example is:
655 \begin{verbatim}
656 animals = ['mollusk',
657 'albatross',
658 'rat',
659 'penguin',
660 'python',
662 # ...
663 for a in animals:
664 print a
665 \end{verbatim}
667 Here, you want to mark the strings in the \code{animals} list as being
668 translatable, but you don't actually want to translate them until they
669 are printed.
671 Here is one way you can handle this situation:
673 \begin{verbatim}
674 def _(message): return message
676 animals = [_('mollusk'),
677 _('albatross'),
678 _('rat'),
679 _('penguin'),
680 _('python'),
683 del _
685 # ...
686 for a in animals:
687 print _(a)
688 \end{verbatim}
690 This works because the dummy definition of \function{_()} simply returns
691 the string unchanged. And this dummy definition will temporarily
692 override any definition of \function{_()} in the built-in namespace
693 (until the \keyword{del} command).
694 Take care, though if you have a previous definition of \function{_} in
695 the local namespace.
697 Note that the second use of \function{_()} will not identify ``a'' as
698 being translatable to the \program{pygettext} program, since it is not
699 a string.
701 Another way to handle this is with the following example:
703 \begin{verbatim}
704 def N_(message): return message
706 animals = [N_('mollusk'),
707 N_('albatross'),
708 N_('rat'),
709 N_('penguin'),
710 N_('python'),
713 # ...
714 for a in animals:
715 print _(a)
716 \end{verbatim}
718 In this case, you are marking translatable strings with the function
719 \function{N_()},\footnote{The choice of \function{N_()} here is totally
720 arbitrary; it could have just as easily been
721 \function{MarkThisStringForTranslation()}.
722 } which won't conflict with any definition of
723 \function{_()}. However, you will need to teach your message extraction
724 program to look for translatable strings marked with \function{N_()}.
725 \program{pygettext} and \program{xpot} both support this through the
726 use of command line switches.
728 \subsubsection{\function{gettext()} vs. \function{lgettext()}}
729 In Python 2.4 the \function{lgettext()} family of functions were
730 introduced. The intention of these functions is to provide an
731 alternative which is more compliant with the current
732 implementation of GNU gettext. Unlike \function{gettext()}, which
733 returns strings encoded with the same codeset used in the
734 translation file, \function{lgettext()} will return strings
735 encoded with the preferred system encoding, as returned by
736 \function{locale.getpreferredencoding()}. Also notice that
737 Python 2.4 introduces new functions to explicitly choose
738 the codeset used in translated strings. If a codeset is explicitly
739 set, even \function{lgettext()} will return translated strings in
740 the requested codeset, as would be expected in the GNU gettext
741 implementation.
743 \subsection{Acknowledgements}
745 The following people contributed code, feedback, design suggestions,
746 previous implementations, and valuable experience to the creation of
747 this module:
749 \begin{itemize}
750 \item Peter Funk
751 \item James Henstridge
752 \item Juan David Ib\'a\~nez Palomar
753 \item Marc-Andr\'e Lemburg
754 \item Martin von L\"owis
755 \item Fran\c cois Pinard
756 \item Barry Warsaw
757 \item Gustavo Niemeyer
758 \end{itemize}