/Doc/library/gettext.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 767 lines · 514 code · 253 blank · 0 comment · 0 complexity · 50bc20a3e2e05c76c030eac60de1dd87 MD5 · raw file

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