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