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