PageRenderTime 46ms CodeModel.GetById 16ms app.highlight 23ms RepoModel.GetById 1ms app.codeStats 0ms

/Doc/library/locale.rst

http://unladen-swallow.googlecode.com/
ReStructuredText | 578 lines | 380 code | 198 blank | 0 comment | 0 complexity | d98cb5f539a00ceeca5e24c3657e6e72 MD5 | raw file
  1
  2:mod:`locale` --- Internationalization services
  3===============================================
  4
  5.. module:: locale
  6   :synopsis: Internationalization services.
  7.. moduleauthor:: Martin von Lรถwis <martin@v.loewis.de>
  8.. sectionauthor:: Martin von Lรถwis <martin@v.loewis.de>
  9
 10
 11The :mod:`locale` module opens access to the POSIX locale database and
 12functionality. The POSIX locale mechanism allows programmers to deal with
 13certain cultural issues in an application, without requiring the programmer to
 14know all the specifics of each country where the software is executed.
 15
 16.. index:: module: _locale
 17
 18The :mod:`locale` module is implemented on top of the :mod:`_locale` module,
 19which in turn uses an ANSI C locale implementation if available.
 20
 21The :mod:`locale` module defines the following exception and functions:
 22
 23
 24.. exception:: Error
 25
 26   Exception raised when :func:`setlocale` fails.
 27
 28
 29.. function:: setlocale(category[, locale])
 30
 31   If *locale* is specified, it may be a string, a tuple of the form ``(language
 32   code, encoding)``, or ``None``. If it is a tuple, it is converted to a string
 33   using the locale aliasing engine.  If *locale* is given and not ``None``,
 34   :func:`setlocale` modifies the locale setting for the *category*.  The available
 35   categories are listed in the data description below.  The value is the name of a
 36   locale.  An empty string specifies the user's default settings. If the
 37   modification of the locale fails, the exception :exc:`Error` is raised.  If
 38   successful, the new locale setting is returned.
 39
 40   If *locale* is omitted or ``None``, the current setting for *category* is
 41   returned.
 42
 43   :func:`setlocale` is not thread safe on most systems. Applications typically
 44   start with a call of ::
 45
 46      import locale
 47      locale.setlocale(locale.LC_ALL, '')
 48
 49   This sets the locale for all categories to the user's default setting (typically
 50   specified in the :envvar:`LANG` environment variable).  If the locale is not
 51   changed thereafter, using multithreading should not cause problems.
 52
 53   .. versionchanged:: 2.0
 54      Added support for tuple values of the *locale* parameter.
 55
 56
 57.. function:: localeconv()
 58
 59   Returns the database of the local conventions as a dictionary. This dictionary
 60   has the following strings as keys:
 61
 62   +----------------------+-------------------------------------+--------------------------------+
 63   | Category             | Key                                 | Meaning                        |
 64   +======================+=====================================+================================+
 65   | :const:`LC_NUMERIC`  | ``'decimal_point'``                 | Decimal point character.       |
 66   +----------------------+-------------------------------------+--------------------------------+
 67   |                      | ``'grouping'``                      | Sequence of numbers specifying |
 68   |                      |                                     | which relative positions the   |
 69   |                      |                                     | ``'thousands_sep'`` is         |
 70   |                      |                                     | expected.  If the sequence is  |
 71   |                      |                                     | terminated with                |
 72   |                      |                                     | :const:`CHAR_MAX`, no further  |
 73   |                      |                                     | grouping is performed. If the  |
 74   |                      |                                     | sequence terminates with a     |
 75   |                      |                                     | ``0``,  the last group size is |
 76   |                      |                                     | repeatedly used.               |
 77   +----------------------+-------------------------------------+--------------------------------+
 78   |                      | ``'thousands_sep'``                 | Character used between groups. |
 79   +----------------------+-------------------------------------+--------------------------------+
 80   | :const:`LC_MONETARY` | ``'int_curr_symbol'``               | International currency symbol. |
 81   +----------------------+-------------------------------------+--------------------------------+
 82   |                      | ``'currency_symbol'``               | Local currency symbol.         |
 83   +----------------------+-------------------------------------+--------------------------------+
 84   |                      | ``'p_cs_precedes/n_cs_precedes'``   | Whether the currency symbol    |
 85   |                      |                                     | precedes the value (for        |
 86   |                      |                                     | positive resp. negative        |
 87   |                      |                                     | values).                       |
 88   +----------------------+-------------------------------------+--------------------------------+
 89   |                      | ``'p_sep_by_space/n_sep_by_space'`` | Whether the currency symbol is |
 90   |                      |                                     | separated from the value  by a |
 91   |                      |                                     | space (for positive resp.      |
 92   |                      |                                     | negative values).              |
 93   +----------------------+-------------------------------------+--------------------------------+
 94   |                      | ``'mon_decimal_point'``             | Decimal point used for         |
 95   |                      |                                     | monetary values.               |
 96   +----------------------+-------------------------------------+--------------------------------+
 97   |                      | ``'frac_digits'``                   | Number of fractional digits    |
 98   |                      |                                     | used in local formatting of    |
 99   |                      |                                     | monetary values.               |
100   +----------------------+-------------------------------------+--------------------------------+
101   |                      | ``'int_frac_digits'``               | Number of fractional digits    |
102   |                      |                                     | used in international          |
103   |                      |                                     | formatting of monetary values. |
104   +----------------------+-------------------------------------+--------------------------------+
105   |                      | ``'mon_thousands_sep'``             | Group separator used for       |
106   |                      |                                     | monetary values.               |
107   +----------------------+-------------------------------------+--------------------------------+
108   |                      | ``'mon_grouping'``                  | Equivalent to ``'grouping'``,  |
109   |                      |                                     | used for monetary values.      |
110   +----------------------+-------------------------------------+--------------------------------+
111   |                      | ``'positive_sign'``                 | Symbol used to annotate a      |
112   |                      |                                     | positive monetary value.       |
113   +----------------------+-------------------------------------+--------------------------------+
114   |                      | ``'negative_sign'``                 | Symbol used to annotate a      |
115   |                      |                                     | negative monetary value.       |
116   +----------------------+-------------------------------------+--------------------------------+
117   |                      | ``'p_sign_posn/n_sign_posn'``       | The position of the sign (for  |
118   |                      |                                     | positive resp. negative        |
119   |                      |                                     | values), see below.            |
120   +----------------------+-------------------------------------+--------------------------------+
121
122   All numeric values can be set to :const:`CHAR_MAX` to indicate that there is no
123   value specified in this locale.
124
125   The possible values for ``'p_sign_posn'`` and ``'n_sign_posn'`` are given below.
126
127   +--------------+-----------------------------------------+
128   | Value        | Explanation                             |
129   +==============+=========================================+
130   | ``0``        | Currency and value are surrounded by    |
131   |              | parentheses.                            |
132   +--------------+-----------------------------------------+
133   | ``1``        | The sign should precede the value and   |
134   |              | currency symbol.                        |
135   +--------------+-----------------------------------------+
136   | ``2``        | The sign should follow the value and    |
137   |              | currency symbol.                        |
138   +--------------+-----------------------------------------+
139   | ``3``        | The sign should immediately precede the |
140   |              | value.                                  |
141   +--------------+-----------------------------------------+
142   | ``4``        | The sign should immediately follow the  |
143   |              | value.                                  |
144   +--------------+-----------------------------------------+
145   | ``CHAR_MAX`` | Nothing is specified in this locale.    |
146   +--------------+-----------------------------------------+
147
148
149.. function:: nl_langinfo(option)
150
151   Return some locale-specific information as a string. This function is not
152   available on all systems, and the set of possible options might also vary across
153   platforms. The possible argument values are numbers, for which symbolic
154   constants are available in the locale module.
155
156
157.. function:: getdefaultlocale([envvars])
158
159   Tries to determine the default locale settings and returns them as a tuple of
160   the form ``(language code, encoding)``.
161
162   According to POSIX, a program which has not called ``setlocale(LC_ALL, '')``
163   runs using the portable ``'C'`` locale.  Calling ``setlocale(LC_ALL, '')`` lets
164   it use the default locale as defined by the :envvar:`LANG` variable.  Since we
165   do not want to interfere with the current locale setting we thus emulate the
166   behavior in the way described above.
167
168   To maintain compatibility with other platforms, not only the :envvar:`LANG`
169   variable is tested, but a list of variables given as envvars parameter.  The
170   first found to be defined will be used.  *envvars* defaults to the search path
171   used in GNU gettext; it must always contain the variable name ``LANG``.  The GNU
172   gettext search path contains ``'LANGUAGE'``, ``'LC_ALL'``, ``'LC_CTYPE'``, and
173   ``'LANG'``, in that order.
174
175   Except for the code ``'C'``, the language code corresponds to :rfc:`1766`.
176   *language code* and *encoding* may be ``None`` if their values cannot be
177   determined.
178
179   .. versionadded:: 2.0
180
181
182.. function:: getlocale([category])
183
184   Returns the current setting for the given locale category as sequence containing
185   *language code*, *encoding*. *category* may be one of the :const:`LC_\*` values
186   except :const:`LC_ALL`.  It defaults to :const:`LC_CTYPE`.
187
188   Except for the code ``'C'``, the language code corresponds to :rfc:`1766`.
189   *language code* and *encoding* may be ``None`` if their values cannot be
190   determined.
191
192   .. versionadded:: 2.0
193
194
195.. function:: getpreferredencoding([do_setlocale])
196
197   Return the encoding used for text data, according to user preferences.  User
198   preferences are expressed differently on different systems, and might not be
199   available programmatically on some systems, so this function only returns a
200   guess.
201
202   On some systems, it is necessary to invoke :func:`setlocale` to obtain the user
203   preferences, so this function is not thread-safe. If invoking setlocale is not
204   necessary or desired, *do_setlocale* should be set to ``False``.
205
206   .. versionadded:: 2.3
207
208
209.. function:: normalize(localename)
210
211   Returns a normalized locale code for the given locale name.  The returned locale
212   code is formatted for use with :func:`setlocale`.  If normalization fails, the
213   original name is returned unchanged.
214
215   If the given encoding is not known, the function defaults to the default
216   encoding for the locale code just like :func:`setlocale`.
217
218   .. versionadded:: 2.0
219
220
221.. function:: resetlocale([category])
222
223   Sets the locale for *category* to the default setting.
224
225   The default setting is determined by calling :func:`getdefaultlocale`.
226   *category* defaults to :const:`LC_ALL`.
227
228   .. versionadded:: 2.0
229
230
231.. function:: strcoll(string1, string2)
232
233   Compares two strings according to the current :const:`LC_COLLATE` setting. As
234   any other compare function, returns a negative, or a positive value, or ``0``,
235   depending on whether *string1* collates before or after *string2* or is equal to
236   it.
237
238
239.. function:: strxfrm(string)
240
241   .. index:: builtin: cmp
242
243   Transforms a string to one that can be used for the built-in function
244   :func:`cmp`, and still returns locale-aware results.  This function can be used
245   when the same string is compared repeatedly, e.g. when collating a sequence of
246   strings.
247
248
249.. function:: format(format, val[, grouping[, monetary]])
250
251   Formats a number *val* according to the current :const:`LC_NUMERIC` setting.
252   The format follows the conventions of the ``%`` operator.  For floating point
253   values, the decimal point is modified if appropriate.  If *grouping* is true,
254   also takes the grouping into account.
255
256   If *monetary* is true, the conversion uses monetary thousands separator and
257   grouping strings.
258
259   Please note that this function will only work for exactly one %char specifier.
260   For whole format strings, use :func:`format_string`.
261
262   .. versionchanged:: 2.5
263      Added the *monetary* parameter.
264
265
266.. function:: format_string(format, val[, grouping])
267
268   Processes formatting specifiers as in ``format % val``, but takes the current
269   locale settings into account.
270
271   .. versionadded:: 2.5
272
273
274.. function:: currency(val[, symbol[, grouping[, international]]])
275
276   Formats a number *val* according to the current :const:`LC_MONETARY` settings.
277
278   The returned string includes the currency symbol if *symbol* is true, which is
279   the default. If *grouping* is true (which is not the default), grouping is done
280   with the value. If *international* is true (which is not the default), the
281   international currency symbol is used.
282
283   Note that this function will not work with the 'C' locale, so you have to set a
284   locale via :func:`setlocale` first.
285
286   .. versionadded:: 2.5
287
288
289.. function:: str(float)
290
291   Formats a floating point number using the same format as the built-in function
292   ``str(float)``, but takes the decimal point into account.
293
294
295.. function:: atof(string)
296
297   Converts a string to a floating point number, following the :const:`LC_NUMERIC`
298   settings.
299
300
301.. function:: atoi(string)
302
303   Converts a string to an integer, following the :const:`LC_NUMERIC` conventions.
304
305
306.. data:: LC_CTYPE
307
308   .. index:: module: string
309
310   Locale category for the character type functions.  Depending on the settings of
311   this category, the functions of module :mod:`string` dealing with case change
312   their behaviour.
313
314
315.. data:: LC_COLLATE
316
317   Locale category for sorting strings.  The functions :func:`strcoll` and
318   :func:`strxfrm` of the :mod:`locale` module are affected.
319
320
321.. data:: LC_TIME
322
323   Locale category for the formatting of time.  The function :func:`time.strftime`
324   follows these conventions.
325
326
327.. data:: LC_MONETARY
328
329   Locale category for formatting of monetary values.  The available options are
330   available from the :func:`localeconv` function.
331
332
333.. data:: LC_MESSAGES
334
335   Locale category for message display. Python currently does not support
336   application specific locale-aware messages.  Messages displayed by the operating
337   system, like those returned by :func:`os.strerror` might be affected by this
338   category.
339
340
341.. data:: LC_NUMERIC
342
343   Locale category for formatting numbers.  The functions :func:`format`,
344   :func:`atoi`, :func:`atof` and :func:`str` of the :mod:`locale` module are
345   affected by that category.  All other numeric formatting operations are not
346   affected.
347
348
349.. data:: LC_ALL
350
351   Combination of all locale settings.  If this flag is used when the locale is
352   changed, setting the locale for all categories is attempted. If that fails for
353   any category, no category is changed at all.  When the locale is retrieved using
354   this flag, a string indicating the setting for all categories is returned. This
355   string can be later used to restore the settings.
356
357
358.. data:: CHAR_MAX
359
360   This is a symbolic constant used for different values returned by
361   :func:`localeconv`.
362
363The :func:`nl_langinfo` function accepts one of the following keys. Most
364descriptions are taken from the corresponding description in the GNU C library.
365
366
367.. data:: CODESET
368
369   Return a string with the name of the character encoding used in the selected
370   locale.
371
372
373.. data:: D_T_FMT
374
375   Return a string that can be used as a format string for strftime(3) to represent
376   time and date in a locale-specific way.
377
378
379.. data:: D_FMT
380
381   Return a string that can be used as a format string for strftime(3) to represent
382   a date in a locale-specific way.
383
384
385.. data:: T_FMT
386
387   Return a string that can be used as a format string for strftime(3) to represent
388   a time in a locale-specific way.
389
390
391.. data:: T_FMT_AMPM
392
393   The return value can be used as a format string for 'strftime' to represent time
394   in the am/pm format.
395
396
397.. data:: DAY_1 ... DAY_7
398
399   Return name of the n-th day of the week.
400
401   .. note::
402
403      This follows the US convention of :const:`DAY_1` being Sunday, not the
404      international convention (ISO 8601) that Monday is the first day of the week.
405
406
407.. data:: ABDAY_1 ... ABDAY_7
408
409   Return abbreviated name of the n-th day of the week.
410
411
412.. data:: MON_1 ... MON_12
413
414   Return name of the n-th month.
415
416
417.. data:: ABMON_1 ... ABMON_12
418
419   Return abbreviated name of the n-th month.
420
421
422.. data:: RADIXCHAR
423
424   Return radix character (decimal dot, decimal comma, etc.)
425
426
427.. data:: THOUSEP
428
429   Return separator character for thousands (groups of three digits).
430
431
432.. data:: YESEXPR
433
434   Return a regular expression that can be used with the regex function to
435   recognize a positive response to a yes/no question.
436
437   .. note::
438
439      The expression is in the syntax suitable for the :cfunc:`regex` function from
440      the C library, which might differ from the syntax used in :mod:`re`.
441
442
443.. data:: NOEXPR
444
445   Return a regular expression that can be used with the regex(3) function to
446   recognize a negative response to a yes/no question.
447
448
449.. data:: CRNCYSTR
450
451   Return the currency symbol, preceded by "-" if the symbol should appear before
452   the value, "+" if the symbol should appear after the value, or "." if the symbol
453   should replace the radix character.
454
455
456.. data:: ERA
457
458   The return value represents the era used in the current locale.
459
460   Most locales do not define this value.  An example of a locale which does define
461   this value is the Japanese one.  In Japan, the traditional representation of
462   dates includes the name of the era corresponding to the then-emperor's reign.
463
464   Normally it should not be necessary to use this value directly. Specifying the
465   ``E`` modifier in their format strings causes the :func:`strftime` function to
466   use this information.  The format of the returned string is not specified, and
467   therefore you should not assume knowledge of it on different systems.
468
469
470.. data:: ERA_YEAR
471
472   The return value gives the year in the relevant era of the locale.
473
474
475.. data:: ERA_D_T_FMT
476
477   This return value can be used as a format string for :func:`strftime` to
478   represent dates and times in a locale-specific era-based way.
479
480
481.. data:: ERA_D_FMT
482
483   This return value can be used as a format string for :func:`strftime` to
484   represent time in a locale-specific era-based way.
485
486
487.. data:: ALT_DIGITS
488
489   The return value is a representation of up to 100 values used to represent the
490   values 0 to 99.
491
492Example::
493
494   >>> import locale
495   >>> loc = locale.getlocale() # get current locale
496   >>> locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform
497   >>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut
498   >>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale
499   >>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale
500   >>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale
501
502
503Background, details, hints, tips and caveats
504--------------------------------------------
505
506The C standard defines the locale as a program-wide property that may be
507relatively expensive to change.  On top of that, some implementation are broken
508in such a way that frequent locale changes may cause core dumps.  This makes the
509locale somewhat painful to use correctly.
510
511Initially, when a program is started, the locale is the ``C`` locale, no matter
512what the user's preferred locale is.  The program must explicitly say that it
513wants the user's preferred locale settings by calling ``setlocale(LC_ALL, '')``.
514
515It is generally a bad idea to call :func:`setlocale` in some library routine,
516since as a side effect it affects the entire program.  Saving and restoring it
517is almost as bad: it is expensive and affects other threads that happen to run
518before the settings have been restored.
519
520If, when coding a module for general use, you need a locale independent version
521of an operation that is affected by the locale (such as :func:`string.lower`, or
522certain formats used with :func:`time.strftime`), you will have to find a way to
523do it without using the standard library routine.  Even better is convincing
524yourself that using locale settings is okay.  Only as a last resort should you
525document that your module is not compatible with non-\ ``C`` locale settings.
526
527.. index:: module: string
528
529The case conversion functions in the :mod:`string` module are affected by the
530locale settings.  When a call to the :func:`setlocale` function changes the
531:const:`LC_CTYPE` settings, the variables ``string.lowercase``,
532``string.uppercase`` and ``string.letters`` are recalculated.  Note that code
533that uses these variable through ':keyword:`from` ... :keyword:`import` ...',
534e.g. ``from string import letters``, is not affected by subsequent
535:func:`setlocale` calls.
536
537The only way to perform numeric operations according to the locale is to use the
538special functions defined by this module: :func:`atof`, :func:`atoi`,
539:func:`format`, :func:`str`.
540
541
542.. _embedding-locale:
543
544For extension writers and programs that embed Python
545----------------------------------------------------
546
547Extension modules should never call :func:`setlocale`, except to find out what
548the current locale is.  But since the return value can only be used portably to
549restore it, that is not very useful (except perhaps to find out whether or not
550the locale is ``C``).
551
552When Python code uses the :mod:`locale` module to change the locale, this also
553affects the embedding application.  If the embedding application doesn't want
554this to happen, it should remove the :mod:`_locale` extension module (which does
555all the work) from the table of built-in modules in the :file:`config.c` file,
556and make sure that the :mod:`_locale` module is not accessible as a shared
557library.
558
559
560.. _locale-gettext:
561
562Access to message catalogs
563--------------------------
564
565The locale module exposes the C library's gettext interface on systems that
566provide this interface.  It consists of the functions :func:`gettext`,
567:func:`dgettext`, :func:`dcgettext`, :func:`textdomain`, :func:`bindtextdomain`,
568and :func:`bind_textdomain_codeset`.  These are similar to the same functions in
569the :mod:`gettext` module, but use the C library's binary format for message
570catalogs, and the C library's search algorithms for locating message catalogs.
571
572Python applications should normally find no need to invoke these functions, and
573should use :mod:`gettext` instead.  A known exception to this rule are
574applications that link use additional C libraries which internally invoke
575:cfunc:`gettext` or :func:`dcgettext`.  For these applications, it may be
576necessary to bind the text domain, so that the libraries can properly locate
577their message catalogs.
578