blob: 1940ec99fd14fd2975d17d3b1441fae8422edb38 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`gettext` --- Multilingual internationalization services
3=============================================================
4
5.. module:: gettext
6 :synopsis: Multilingual internationalization services.
7.. moduleauthor:: Barry A. Warsaw <barry@zope.com>
8.. sectionauthor:: Barry A. Warsaw <barry@zope.com>
9
10
11The :mod:`gettext` module provides internationalization (I18N) and localization
12(L10N) services for your Python modules and applications. It supports both the
13GNU ``gettext`` message catalog API and a higher level, class-based API that may
14be more appropriate for Python files. The interface described below allows you
15to write your module and application messages in one natural language, and
16provide a catalog of translated messages for running under different natural
17languages.
18
19Some hints on localizing your Python modules and applications are also given.
20
21
22GNU :program:`gettext` API
23--------------------------
24
25The :mod:`gettext` module defines the following API, which is very similar to
26the GNU :program:`gettext` API. If you use this API you will affect the
27translation of your entire application globally. Often this is what you want if
28your application is monolingual, with the choice of language dependent on the
29locale of your user. If you are localizing a Python module, or if your
30application needs to switch languages on the fly, you probably want to use the
31class-based API instead.
32
33
34.. function:: bindtextdomain(domain[, localedir])
35
36 Bind the *domain* to the locale directory *localedir*. More concretely,
37 :mod:`gettext` will look for binary :file:`.mo` files for the given domain using
38 the path (on Unix): :file:`localedir/language/LC_MESSAGES/domain.mo`, where
39 *languages* is searched for in the environment variables :envvar:`LANGUAGE`,
40 :envvar:`LC_ALL`, :envvar:`LC_MESSAGES`, and :envvar:`LANG` respectively.
41
42 If *localedir* is omitted or ``None``, then the current binding for *domain* is
43 returned. [#]_
44
45
46.. function:: bind_textdomain_codeset(domain[, codeset])
47
48 Bind the *domain* to *codeset*, changing the encoding of strings returned by the
49 :func:`gettext` family of functions. If *codeset* is omitted, then the current
50 binding is returned.
51
Georg Brandl116aa622007-08-15 14:28:22 +000052
53.. function:: textdomain([domain])
54
55 Change or query the current global domain. If *domain* is ``None``, then the
56 current global domain is returned, otherwise the global domain is set to
57 *domain*, which is returned.
58
59
60.. function:: gettext(message)
61
62 Return the localized translation of *message*, based on the current global
63 domain, language, and locale directory. This function is usually aliased as
64 :func:`_` in the local namespace (see examples below).
65
66
67.. function:: lgettext(message)
68
69 Equivalent to :func:`gettext`, but the translation is returned in the preferred
70 system encoding, if no other encoding was explicitly set with
71 :func:`bind_textdomain_codeset`.
72
Georg Brandl116aa622007-08-15 14:28:22 +000073
74.. function:: dgettext(domain, message)
75
76 Like :func:`gettext`, but look the message up in the specified *domain*.
77
78
79.. function:: ldgettext(domain, message)
80
81 Equivalent to :func:`dgettext`, but the translation is returned in the preferred
82 system encoding, if no other encoding was explicitly set with
83 :func:`bind_textdomain_codeset`.
84
Georg Brandl116aa622007-08-15 14:28:22 +000085
86.. function:: ngettext(singular, plural, n)
87
88 Like :func:`gettext`, but consider plural forms. If a translation is found,
89 apply the plural formula to *n*, and return the resulting message (some
90 languages have more than two plural forms). If no translation is found, return
91 *singular* if *n* is 1; return *plural* otherwise.
92
93 The Plural formula is taken from the catalog header. It is a C or Python
94 expression that has a free variable *n*; the expression evaluates to the index
95 of the plural in the catalog. See the GNU gettext documentation for the precise
96 syntax to be used in :file:`.po` files and the formulas for a variety of
97 languages.
98
Georg Brandl116aa622007-08-15 14:28:22 +000099
100.. function:: lngettext(singular, plural, n)
101
102 Equivalent to :func:`ngettext`, but the translation is returned in the preferred
103 system encoding, if no other encoding was explicitly set with
104 :func:`bind_textdomain_codeset`.
105
Georg Brandl116aa622007-08-15 14:28:22 +0000106
107.. function:: dngettext(domain, singular, plural, n)
108
109 Like :func:`ngettext`, but look the message up in the specified *domain*.
110
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112.. function:: ldngettext(domain, singular, plural, n)
113
114 Equivalent to :func:`dngettext`, but the translation is returned in the
115 preferred system encoding, if no other encoding was explicitly set with
116 :func:`bind_textdomain_codeset`.
117
Georg Brandl116aa622007-08-15 14:28:22 +0000118
119Note that GNU :program:`gettext` also defines a :func:`dcgettext` method, but
120this was deemed not useful and so it is currently unimplemented.
121
122Here's an example of typical usage for this API::
123
124 import gettext
125 gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
126 gettext.textdomain('myapplication')
127 _ = gettext.gettext
128 # ...
Georg Brandl6911e3c2007-09-04 07:15:32 +0000129 print(_('This is a translatable string.'))
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131
132Class-based API
133---------------
134
135The class-based API of the :mod:`gettext` module gives you more flexibility and
136greater convenience than the GNU :program:`gettext` API. It is the recommended
137way of localizing your Python applications and modules. :mod:`gettext` defines
138a "translations" class which implements the parsing of GNU :file:`.mo` format
139files, and has methods for returning either standard 8-bit strings or Unicode
140strings. Instances of this "translations" class can also install themselves in
141the built-in namespace as the function :func:`_`.
142
143
144.. function:: find(domain[, localedir[, languages[, all]]])
145
146 This function implements the standard :file:`.mo` file search algorithm. It
147 takes a *domain*, identical to what :func:`textdomain` takes. Optional
148 *localedir* is as in :func:`bindtextdomain` Optional *languages* is a list of
149 strings, where each string is a language code.
150
151 If *localedir* is not given, then the default system locale directory is used.
152 [#]_ If *languages* is not given, then the following environment variables are
153 searched: :envvar:`LANGUAGE`, :envvar:`LC_ALL`, :envvar:`LC_MESSAGES`, and
154 :envvar:`LANG`. The first one returning a non-empty value is used for the
155 *languages* variable. The environment variables should contain a colon separated
156 list of languages, which will be split on the colon to produce the expected list
157 of language code strings.
158
159 :func:`find` then expands and normalizes the languages, and then iterates
160 through them, searching for an existing file built of these components:
161
162 :file:`localedir/language/LC_MESSAGES/domain.mo`
163
164 The first such file name that exists is returned by :func:`find`. If no such
165 file is found, then ``None`` is returned. If *all* is given, it returns a list
166 of all file names, in the order in which they appear in the languages list or
167 the environment variables.
168
169
170.. function:: translation(domain[, localedir[, languages[, class_[, fallback[, codeset]]]]])
171
172 Return a :class:`Translations` instance based on the *domain*, *localedir*, and
173 *languages*, which are first passed to :func:`find` to get a list of the
174 associated :file:`.mo` file paths. Instances with identical :file:`.mo` file
175 names are cached. The actual class instantiated is either *class_* if provided,
176 otherwise :class:`GNUTranslations`. The class's constructor must take a single
177 file object argument. If provided, *codeset* will change the charset used to
178 encode translated strings.
179
180 If multiple files are found, later files are used as fallbacks for earlier ones.
181 To allow setting the fallback, :func:`copy.copy` is used to clone each
182 translation object from the cache; the actual instance data is still shared with
183 the cache.
184
185 If no :file:`.mo` file is found, this function raises :exc:`IOError` if
186 *fallback* is false (which is the default), and returns a
187 :class:`NullTranslations` instance if *fallback* is true.
188
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190.. function:: install(domain[, localedir[, unicode [, codeset[, names]]]])
191
192 This installs the function :func:`_` in Python's builtin namespace, based on
193 *domain*, *localedir*, and *codeset* which are passed to the function
194 :func:`translation`. The *unicode* flag is passed to the resulting translation
195 object's :meth:`install` method.
196
197 For the *names* parameter, please see the description of the translation
198 object's :meth:`install` method.
199
200 As seen below, you usually mark the strings in your application that are
201 candidates for translation, by wrapping them in a call to the :func:`_`
202 function, like this::
203
Georg Brandl6911e3c2007-09-04 07:15:32 +0000204 print(_('This string will be translated.'))
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206 For convenience, you want the :func:`_` function to be installed in Python's
207 builtin namespace, so it is easily accessible in all modules of your
208 application.
209
Georg Brandl116aa622007-08-15 14:28:22 +0000210
211The :class:`NullTranslations` class
212^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
213
214Translation classes are what actually implement the translation of original
215source file message strings to translated message strings. The base class used
216by all translation classes is :class:`NullTranslations`; this provides the basic
217interface you can use to write your own specialized translation classes. Here
218are the methods of :class:`NullTranslations`:
219
220
221.. method:: NullTranslations.__init__([fp])
222
223 Takes an optional file object *fp*, which is ignored by the base class.
224 Initializes "protected" instance variables *_info* and *_charset* which are set
225 by derived classes, as well as *_fallback*, which is set through
226 :meth:`add_fallback`. It then calls ``self._parse(fp)`` if *fp* is not
227 ``None``.
228
229
230.. method:: NullTranslations._parse(fp)
231
232 No-op'd in the base class, this method takes file object *fp*, and reads the
233 data from the file, initializing its message catalog. If you have an
234 unsupported message catalog file format, you should override this method to
235 parse your format.
236
237
238.. method:: NullTranslations.add_fallback(fallback)
239
240 Add *fallback* as the fallback object for the current translation object. A
241 translation object should consult the fallback if it cannot provide a
242 translation for a given message.
243
244
245.. method:: NullTranslations.gettext(message)
246
247 If a fallback has been set, forward :meth:`gettext` to the fallback. Otherwise,
248 return the translated message. Overridden in derived classes.
249
250
251.. method:: NullTranslations.lgettext(message)
252
253 If a fallback has been set, forward :meth:`lgettext` to the fallback. Otherwise,
254 return the translated message. Overridden in derived classes.
255
Georg Brandl116aa622007-08-15 14:28:22 +0000256
257.. method:: NullTranslations.ugettext(message)
258
259 If a fallback has been set, forward :meth:`ugettext` to the fallback. Otherwise,
260 return the translated message as a Unicode string. Overridden in derived
261 classes.
262
263
264.. method:: NullTranslations.ngettext(singular, plural, n)
265
266 If a fallback has been set, forward :meth:`ngettext` to the fallback. Otherwise,
267 return the translated message. Overridden in derived classes.
268
Georg Brandl116aa622007-08-15 14:28:22 +0000269
270.. method:: NullTranslations.lngettext(singular, plural, n)
271
272 If a fallback has been set, forward :meth:`ngettext` to the fallback. Otherwise,
273 return the translated message. Overridden in derived classes.
274
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276.. method:: NullTranslations.ungettext(singular, plural, n)
277
278 If a fallback has been set, forward :meth:`ungettext` to the fallback.
279 Otherwise, return the translated message as a Unicode string. Overridden in
280 derived classes.
281
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283.. method:: NullTranslations.info()
284
285 Return the "protected" :attr:`_info` variable.
286
287
288.. method:: NullTranslations.charset()
289
290 Return the "protected" :attr:`_charset` variable.
291
292
293.. method:: NullTranslations.output_charset()
294
295 Return the "protected" :attr:`_output_charset` variable, which defines the
296 encoding used to return translated messages.
297
Georg Brandl116aa622007-08-15 14:28:22 +0000298
299.. method:: NullTranslations.set_output_charset(charset)
300
301 Change the "protected" :attr:`_output_charset` variable, which defines the
302 encoding used to return translated messages.
303
Georg Brandl116aa622007-08-15 14:28:22 +0000304
305.. method:: NullTranslations.install([unicode [, names]])
306
307 If the *unicode* flag is false, this method installs :meth:`self.gettext` into
308 the built-in namespace, binding it to ``_``. If *unicode* is true, it binds
309 :meth:`self.ugettext` instead. By default, *unicode* is false.
310
311 If the *names* parameter is given, it must be a sequence containing the names of
312 functions you want to install in the builtin namespace in addition to :func:`_`.
313 Supported names are ``'gettext'`` (bound to :meth:`self.gettext` or
314 :meth:`self.ugettext` according to the *unicode* flag), ``'ngettext'`` (bound to
315 :meth:`self.ngettext` or :meth:`self.ungettext` according to the *unicode*
316 flag), ``'lgettext'`` and ``'lngettext'``.
317
318 Note that this is only one way, albeit the most convenient way, to make the
319 :func:`_` function available to your application. Because it affects the entire
320 application globally, and specifically the built-in namespace, localized modules
321 should never install :func:`_`. Instead, they should use this code to make
322 :func:`_` available to their module::
323
324 import gettext
325 t = gettext.translation('mymodule', ...)
326 _ = t.gettext
327
328 This puts :func:`_` only in the module's global namespace and so only affects
329 calls within this module.
330
Georg Brandl116aa622007-08-15 14:28:22 +0000331
332The :class:`GNUTranslations` class
333^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
334
335The :mod:`gettext` module provides one additional class derived from
336:class:`NullTranslations`: :class:`GNUTranslations`. This class overrides
337:meth:`_parse` to enable reading GNU :program:`gettext` format :file:`.mo` files
338in both big-endian and little-endian format. It also coerces both message ids
339and message strings to Unicode.
340
341:class:`GNUTranslations` parses optional meta-data out of the translation
342catalog. It is convention with GNU :program:`gettext` to include meta-data as
343the translation for the empty string. This meta-data is in :rfc:`822`\ -style
344``key: value`` pairs, and should contain the ``Project-Id-Version`` key. If the
345key ``Content-Type`` is found, then the ``charset`` property is used to
346initialize the "protected" :attr:`_charset` instance variable, defaulting to
347``None`` if not found. If the charset encoding is specified, then all message
348ids and message strings read from the catalog are converted to Unicode using
349this encoding. The :meth:`ugettext` method always returns a Unicode, while the
350:meth:`gettext` returns an encoded 8-bit string. For the message id arguments
351of both methods, either Unicode strings or 8-bit strings containing only
352US-ASCII characters are acceptable. Note that the Unicode version of the
353methods (i.e. :meth:`ugettext` and :meth:`ungettext`) are the recommended
354interface to use for internationalized Python programs.
355
356The entire set of key/value pairs are placed into a dictionary and set as the
357"protected" :attr:`_info` instance variable.
358
359If the :file:`.mo` file's magic number is invalid, or if other problems occur
360while reading the file, instantiating a :class:`GNUTranslations` class can raise
361:exc:`IOError`.
362
363The following methods are overridden from the base class implementation:
364
365
366.. method:: GNUTranslations.gettext(message)
367
368 Look up the *message* id in the catalog and return the corresponding message
369 string, as an 8-bit string encoded with the catalog's charset encoding, if
370 known. If there is no entry in the catalog for the *message* id, and a fallback
371 has been set, the look up is forwarded to the fallback's :meth:`gettext` method.
372 Otherwise, the *message* id is returned.
373
374
375.. method:: GNUTranslations.lgettext(message)
376
377 Equivalent to :meth:`gettext`, but the translation is returned in the preferred
378 system encoding, if no other encoding was explicitly set with
379 :meth:`set_output_charset`.
380
Georg Brandl116aa622007-08-15 14:28:22 +0000381
382.. method:: GNUTranslations.ugettext(message)
383
384 Look up the *message* id in the catalog and return the corresponding message
385 string, as a Unicode string. If there is no entry in the catalog for the
386 *message* id, and a fallback has been set, the look up is forwarded to the
387 fallback's :meth:`ugettext` method. Otherwise, the *message* id is returned.
388
389
390.. method:: GNUTranslations.ngettext(singular, plural, n)
391
392 Do a plural-forms lookup of a message id. *singular* is used as the message id
393 for purposes of lookup in the catalog, while *n* is used to determine which
394 plural form to use. The returned message string is an 8-bit string encoded with
395 the catalog's charset encoding, if known.
396
397 If the message id is not found in the catalog, and a fallback is specified, the
398 request is forwarded to the fallback's :meth:`ngettext` method. Otherwise, when
399 *n* is 1 *singular* is returned, and *plural* is returned in all other cases.
400
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402.. method:: GNUTranslations.lngettext(singular, plural, n)
403
404 Equivalent to :meth:`gettext`, but the translation is returned in the preferred
405 system encoding, if no other encoding was explicitly set with
406 :meth:`set_output_charset`.
407
Georg Brandl116aa622007-08-15 14:28:22 +0000408
409.. method:: GNUTranslations.ungettext(singular, plural, n)
410
411 Do a plural-forms lookup of a message id. *singular* is used as the message id
412 for purposes of lookup in the catalog, while *n* is used to determine which
413 plural form to use. The returned message string is a Unicode string.
414
415 If the message id is not found in the catalog, and a fallback is specified, the
416 request is forwarded to the fallback's :meth:`ungettext` method. Otherwise,
417 when *n* is 1 *singular* is returned, and *plural* is returned in all other
418 cases.
419
420 Here is an example::
421
422 n = len(os.listdir('.'))
423 cat = GNUTranslations(somefile)
424 message = cat.ungettext(
425 'There is %(num)d file in this directory',
426 'There are %(num)d files in this directory',
427 n) % {'num': n}
428
Georg Brandl116aa622007-08-15 14:28:22 +0000429
430Solaris message catalog support
431^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
432
433The Solaris operating system defines its own binary :file:`.mo` file format, but
434since no documentation can be found on this format, it is not supported at this
435time.
436
437
438The Catalog constructor
439^^^^^^^^^^^^^^^^^^^^^^^
440
441.. index:: single: GNOME
442
443GNOME uses a version of the :mod:`gettext` module by James Henstridge, but this
444version has a slightly different API. Its documented usage was::
445
446 import gettext
447 cat = gettext.Catalog(domain, localedir)
448 _ = cat.gettext
Georg Brandl6911e3c2007-09-04 07:15:32 +0000449 print(_('hello world'))
Georg Brandl116aa622007-08-15 14:28:22 +0000450
451For compatibility with this older module, the function :func:`Catalog` is an
452alias for the :func:`translation` function described above.
453
454One difference between this module and Henstridge's: his catalog objects
455supported access through a mapping API, but this appears to be unused and so is
456not currently supported.
457
458
459Internationalizing your programs and modules
460--------------------------------------------
461
462Internationalization (I18N) refers to the operation by which a program is made
463aware of multiple languages. Localization (L10N) refers to the adaptation of
464your program, once internationalized, to the local language and cultural habits.
465In order to provide multilingual messages for your Python programs, you need to
466take the following steps:
467
468#. prepare your program or module by specially marking translatable strings
469
470#. run a suite of tools over your marked files to generate raw messages catalogs
471
472#. create language specific translations of the message catalogs
473
474#. use the :mod:`gettext` module so that message strings are properly translated
475
476In order to prepare your code for I18N, you need to look at all the strings in
477your files. Any string that needs to be translated should be marked by wrapping
478it in ``_('...')`` --- that is, a call to the function :func:`_`. For example::
479
480 filename = 'mylog.txt'
481 message = _('writing a log message')
482 fp = open(filename, 'w')
483 fp.write(message)
484 fp.close()
485
486In this example, the string ``'writing a log message'`` is marked as a candidate
487for translation, while the strings ``'mylog.txt'`` and ``'w'`` are not.
488
489The Python distribution comes with two tools which help you generate the message
490catalogs once you've prepared your source code. These may or may not be
491available from a binary distribution, but they can be found in a source
492distribution, in the :file:`Tools/i18n` directory.
493
494The :program:`pygettext` [#]_ program scans all your Python source code looking
495for the strings you previously marked as translatable. It is similar to the GNU
496:program:`gettext` program except that it understands all the intricacies of
497Python source code, but knows nothing about C or C++ source code. You don't
498need GNU ``gettext`` unless you're also going to be translating C code (such as
499C extension modules).
500
501:program:`pygettext` generates textual Uniforum-style human readable message
502catalog :file:`.pot` files, essentially structured human readable files which
503contain every marked string in the source code, along with a placeholder for the
504translation strings. :program:`pygettext` is a command line script that supports
505a similar command line interface as :program:`xgettext`; for details on its use,
506run::
507
508 pygettext.py --help
509
510Copies of these :file:`.pot` files are then handed over to the individual human
511translators who write language-specific versions for every supported natural
512language. They send you back the filled in language-specific versions as a
513:file:`.po` file. Using the :program:`msgfmt.py` [#]_ program (in the
514:file:`Tools/i18n` directory), you take the :file:`.po` files from your
515translators and generate the machine-readable :file:`.mo` binary catalog files.
516The :file:`.mo` files are what the :mod:`gettext` module uses for the actual
517translation processing during run-time.
518
519How you use the :mod:`gettext` module in your code depends on whether you are
520internationalizing a single module or your entire application. The next two
521sections will discuss each case.
522
523
524Localizing your module
525^^^^^^^^^^^^^^^^^^^^^^
526
527If you are localizing your module, you must take care not to make global
528changes, e.g. to the built-in namespace. You should not use the GNU ``gettext``
529API but instead the class-based API.
530
531Let's say your module is called "spam" and the module's various natural language
532translation :file:`.mo` files reside in :file:`/usr/share/locale` in GNU
533:program:`gettext` format. Here's what you would put at the top of your
534module::
535
536 import gettext
537 t = gettext.translation('spam', '/usr/share/locale')
538 _ = t.lgettext
539
540If your translators were providing you with Unicode strings in their :file:`.po`
541files, you'd instead do::
542
543 import gettext
544 t = gettext.translation('spam', '/usr/share/locale')
545 _ = t.ugettext
546
547
548Localizing your application
549^^^^^^^^^^^^^^^^^^^^^^^^^^^
550
551If you are localizing your application, you can install the :func:`_` function
552globally into the built-in namespace, usually in the main driver file of your
553application. This will let all your application-specific files just use
554``_('...')`` without having to explicitly install it in each file.
555
556In the simple case then, you need only add the following bit of code to the main
557driver file of your application::
558
559 import gettext
560 gettext.install('myapplication')
561
562If you need to set the locale directory or the *unicode* flag, you can pass
563these into the :func:`install` function::
564
565 import gettext
566 gettext.install('myapplication', '/usr/share/locale', unicode=1)
567
568
569Changing languages on the fly
570^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
571
572If your program needs to support many languages at the same time, you may want
573to create multiple translation instances and then switch between them
574explicitly, like so::
575
576 import gettext
577
578 lang1 = gettext.translation('myapplication', languages=['en'])
579 lang2 = gettext.translation('myapplication', languages=['fr'])
580 lang3 = gettext.translation('myapplication', languages=['de'])
581
582 # start by using language1
583 lang1.install()
584
585 # ... time goes by, user selects language 2
586 lang2.install()
587
588 # ... more time goes by, user selects language 3
589 lang3.install()
590
591
592Deferred translations
593^^^^^^^^^^^^^^^^^^^^^
594
595In most coding situations, strings are translated where they are coded.
596Occasionally however, you need to mark strings for translation, but defer actual
597translation until later. A classic example is::
598
599 animals = ['mollusk',
600 'albatross',
601 'rat',
602 'penguin',
603 'python',
604 ]
605 # ...
606 for a in animals:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000607 print(a)
Georg Brandl116aa622007-08-15 14:28:22 +0000608
609Here, you want to mark the strings in the ``animals`` list as being
610translatable, but you don't actually want to translate them until they are
611printed.
612
613Here is one way you can handle this situation::
614
615 def _(message): return message
616
617 animals = [_('mollusk'),
618 _('albatross'),
619 _('rat'),
620 _('penguin'),
621 _('python'),
622 ]
623
624 del _
625
626 # ...
627 for a in animals:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000628 print(_(a))
Georg Brandl116aa622007-08-15 14:28:22 +0000629
630This works because the dummy definition of :func:`_` simply returns the string
631unchanged. And this dummy definition will temporarily override any definition
632of :func:`_` in the built-in namespace (until the :keyword:`del` command). Take
633care, though if you have a previous definition of :func:`_` in the local
634namespace.
635
636Note that the second use of :func:`_` will not identify "a" as being
637translatable to the :program:`pygettext` program, since it is not a string.
638
639Another way to handle this is with the following example::
640
641 def N_(message): return message
642
643 animals = [N_('mollusk'),
644 N_('albatross'),
645 N_('rat'),
646 N_('penguin'),
647 N_('python'),
648 ]
649
650 # ...
651 for a in animals:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000652 print(_(a))
Georg Brandl116aa622007-08-15 14:28:22 +0000653
654In this case, you are marking translatable strings with the function :func:`N_`,
655[#]_ which won't conflict with any definition of :func:`_`. However, you will
656need to teach your message extraction program to look for translatable strings
657marked with :func:`N_`. :program:`pygettext` and :program:`xpot` both support
658this through the use of command line switches.
659
660
661:func:`gettext` vs. :func:`lgettext`
662^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
663
664In Python 2.4 the :func:`lgettext` family of functions were introduced. The
665intention of these functions is to provide an alternative which is more
666compliant with the current implementation of GNU gettext. Unlike
667:func:`gettext`, which returns strings encoded with the same codeset used in the
668translation file, :func:`lgettext` will return strings encoded with the
669preferred system encoding, as returned by :func:`locale.getpreferredencoding`.
670Also notice that Python 2.4 introduces new functions to explicitly choose the
671codeset used in translated strings. If a codeset is explicitly set, even
672:func:`lgettext` will return translated strings in the requested codeset, as
673would be expected in the GNU gettext implementation.
674
675
676Acknowledgements
677----------------
678
679The following people contributed code, feedback, design suggestions, previous
680implementations, and valuable experience to the creation of this module:
681
682* Peter Funk
683
684* James Henstridge
685
686* Juan David Ibáñez Palomar
687
688* Marc-André Lemburg
689
690* Martin von Löwis
691
692* François Pinard
693
694* Barry Warsaw
695
696* Gustavo Niemeyer
697
698.. rubric:: Footnotes
699
700.. [#] The default locale directory is system dependent; for example, on RedHat Linux
701 it is :file:`/usr/share/locale`, but on Solaris it is :file:`/usr/lib/locale`.
702 The :mod:`gettext` module does not try to support these system dependent
703 defaults; instead its default is :file:`sys.prefix/share/locale`. For this
704 reason, it is always best to call :func:`bindtextdomain` with an explicit
705 absolute path at the start of your application.
706
707.. [#] See the footnote for :func:`bindtextdomain` above.
708
709.. [#] François Pinard has written a program called :program:`xpot` which does a
710 similar job. It is available as part of his :program:`po-utils` package at http
711 ://po-utils.progiciels-bpi.ca/.
712
713.. [#] :program:`msgfmt.py` is binary compatible with GNU :program:`msgfmt` except that
714 it provides a simpler, all-Python implementation. With this and
715 :program:`pygettext.py`, you generally won't need to install the GNU
716 :program:`gettext` package to internationalize your Python applications.
717
718.. [#] The choice of :func:`N_` here is totally arbitrary; it could have just as easily
719 been :func:`MarkThisStringForTranslation`.
720