blob: f72a44a4381cdee7f6e7ea059486e96f8f64d560 [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
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000228 Transforms a string to one that can be used in locale-aware
229 comparisons. For example, ``strxfrm(s1) < strxfrm(s2)`` is
230 equivalent to ``strcoll(s1, s2) < 0``. This function can be used
231 when the same string is compared repeatedly, e.g. when collating a
232 sequence of strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234
235.. function:: format(format, val[, grouping[, monetary]])
236
237 Formats a number *val* according to the current :const:`LC_NUMERIC` setting.
238 The format follows the conventions of the ``%`` operator. For floating point
239 values, the decimal point is modified if appropriate. If *grouping* is true,
240 also takes the grouping into account.
241
242 If *monetary* is true, the conversion uses monetary thousands separator and
243 grouping strings.
244
245 Please note that this function will only work for exactly one %char specifier.
246 For whole format strings, use :func:`format_string`.
247
Georg Brandl116aa622007-08-15 14:28:22 +0000248
249.. function:: format_string(format, val[, grouping])
250
251 Processes formatting specifiers as in ``format % val``, but takes the current
252 locale settings into account.
253
Georg Brandl116aa622007-08-15 14:28:22 +0000254
255.. function:: currency(val[, symbol[, grouping[, international]]])
256
257 Formats a number *val* according to the current :const:`LC_MONETARY` settings.
258
259 The returned string includes the currency symbol if *symbol* is true, which is
260 the default. If *grouping* is true (which is not the default), grouping is done
261 with the value. If *international* is true (which is not the default), the
262 international currency symbol is used.
263
264 Note that this function will not work with the 'C' locale, so you have to set a
265 locale via :func:`setlocale` first.
266
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268.. function:: str(float)
269
270 Formats a floating point number using the same format as the built-in function
271 ``str(float)``, but takes the decimal point into account.
272
273
274.. function:: atof(string)
275
276 Converts a string to a floating point number, following the :const:`LC_NUMERIC`
277 settings.
278
279
280.. function:: atoi(string)
281
282 Converts a string to an integer, following the :const:`LC_NUMERIC` conventions.
283
284
285.. data:: LC_CTYPE
286
287 .. index:: module: string
288
289 Locale category for the character type functions. Depending on the settings of
290 this category, the functions of module :mod:`string` dealing with case change
291 their behaviour.
292
293
294.. data:: LC_COLLATE
295
296 Locale category for sorting strings. The functions :func:`strcoll` and
297 :func:`strxfrm` of the :mod:`locale` module are affected.
298
299
300.. data:: LC_TIME
301
302 Locale category for the formatting of time. The function :func:`time.strftime`
303 follows these conventions.
304
305
306.. data:: LC_MONETARY
307
308 Locale category for formatting of monetary values. The available options are
309 available from the :func:`localeconv` function.
310
311
312.. data:: LC_MESSAGES
313
314 Locale category for message display. Python currently does not support
315 application specific locale-aware messages. Messages displayed by the operating
316 system, like those returned by :func:`os.strerror` might be affected by this
317 category.
318
319
320.. data:: LC_NUMERIC
321
322 Locale category for formatting numbers. The functions :func:`format`,
323 :func:`atoi`, :func:`atof` and :func:`str` of the :mod:`locale` module are
324 affected by that category. All other numeric formatting operations are not
325 affected.
326
327
328.. data:: LC_ALL
329
330 Combination of all locale settings. If this flag is used when the locale is
331 changed, setting the locale for all categories is attempted. If that fails for
332 any category, no category is changed at all. When the locale is retrieved using
333 this flag, a string indicating the setting for all categories is returned. This
334 string can be later used to restore the settings.
335
336
337.. data:: CHAR_MAX
338
339 This is a symbolic constant used for different values returned by
340 :func:`localeconv`.
341
342The :func:`nl_langinfo` function accepts one of the following keys. Most
343descriptions are taken from the corresponding description in the GNU C library.
344
345
346.. data:: CODESET
347
348 Return a string with the name of the character encoding used in the selected
349 locale.
350
351
352.. data:: D_T_FMT
353
354 Return a string that can be used as a format string for strftime(3) to represent
355 time and date in a locale-specific way.
356
357
358.. data:: D_FMT
359
360 Return a string that can be used as a format string for strftime(3) to represent
361 a date in a locale-specific way.
362
363
364.. data:: T_FMT
365
366 Return a string that can be used as a format string for strftime(3) to represent
367 a time in a locale-specific way.
368
369
370.. data:: T_FMT_AMPM
371
372 The return value can be used as a format string for 'strftime' to represent time
373 in the am/pm format.
374
375
376.. data:: DAY_1 ... DAY_7
377
378 Return name of the n-th day of the week.
379
Georg Brandle720c0a2009-04-27 16:20:50 +0000380 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000381
382 This follows the US convention of :const:`DAY_1` being Sunday, not the
383 international convention (ISO 8601) that Monday is the first day of the week.
384
385
386.. data:: ABDAY_1 ... ABDAY_7
387
388 Return abbreviated name of the n-th day of the week.
389
390
391.. data:: MON_1 ... MON_12
392
393 Return name of the n-th month.
394
395
396.. data:: ABMON_1 ... ABMON_12
397
398 Return abbreviated name of the n-th month.
399
400
401.. data:: RADIXCHAR
402
403 Return radix character (decimal dot, decimal comma, etc.)
404
405
406.. data:: THOUSEP
407
408 Return separator character for thousands (groups of three digits).
409
410
411.. data:: YESEXPR
412
413 Return a regular expression that can be used with the regex function to
414 recognize a positive response to a yes/no question.
415
Georg Brandle720c0a2009-04-27 16:20:50 +0000416 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418 The expression is in the syntax suitable for the :cfunc:`regex` function from
419 the C library, which might differ from the syntax used in :mod:`re`.
420
421
422.. data:: NOEXPR
423
424 Return a regular expression that can be used with the regex(3) function to
425 recognize a negative response to a yes/no question.
426
427
428.. data:: CRNCYSTR
429
430 Return the currency symbol, preceded by "-" if the symbol should appear before
431 the value, "+" if the symbol should appear after the value, or "." if the symbol
432 should replace the radix character.
433
434
435.. data:: ERA
436
437 The return value represents the era used in the current locale.
438
439 Most locales do not define this value. An example of a locale which does define
440 this value is the Japanese one. In Japan, the traditional representation of
441 dates includes the name of the era corresponding to the then-emperor's reign.
442
443 Normally it should not be necessary to use this value directly. Specifying the
444 ``E`` modifier in their format strings causes the :func:`strftime` function to
445 use this information. The format of the returned string is not specified, and
446 therefore you should not assume knowledge of it on different systems.
447
448
449.. data:: ERA_YEAR
450
451 The return value gives the year in the relevant era of the locale.
452
453
454.. data:: ERA_D_T_FMT
455
456 This return value can be used as a format string for :func:`strftime` to
457 represent dates and times in a locale-specific era-based way.
458
459
460.. data:: ERA_D_FMT
461
462 This return value can be used as a format string for :func:`strftime` to
463 represent time in a locale-specific era-based way.
464
465
466.. data:: ALT_DIGITS
467
468 The return value is a representation of up to 100 values used to represent the
469 values 0 to 99.
470
471Example::
472
473 >>> import locale
Benjamin Petersonf608c612008-11-16 18:33:53 +0000474 >>> loc = locale.getlocale() # get current locale
Georg Brandl116aa622007-08-15 14:28:22 +0000475 >>> locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform
Georg Brandl48310cd2009-01-03 21:18:54 +0000476 >>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut
Georg Brandl116aa622007-08-15 14:28:22 +0000477 >>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale
478 >>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale
479 >>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale
480
481
482Background, details, hints, tips and caveats
483--------------------------------------------
484
485The C standard defines the locale as a program-wide property that may be
486relatively expensive to change. On top of that, some implementation are broken
487in such a way that frequent locale changes may cause core dumps. This makes the
488locale somewhat painful to use correctly.
489
490Initially, when a program is started, the locale is the ``C`` locale, no matter
491what the user's preferred locale is. The program must explicitly say that it
492wants the user's preferred locale settings by calling ``setlocale(LC_ALL, '')``.
493
494It is generally a bad idea to call :func:`setlocale` in some library routine,
495since as a side effect it affects the entire program. Saving and restoring it
496is almost as bad: it is expensive and affects other threads that happen to run
497before the settings have been restored.
498
499If, when coding a module for general use, you need a locale independent version
Guido van Rossum8d2ef872007-10-15 15:42:31 +0000500of an operation that is affected by the locale (such as
Georg Brandl116aa622007-08-15 14:28:22 +0000501certain formats used with :func:`time.strftime`), you will have to find a way to
502do it without using the standard library routine. Even better is convincing
503yourself that using locale settings is okay. Only as a last resort should you
504document that your module is not compatible with non-\ ``C`` locale settings.
505
Georg Brandl116aa622007-08-15 14:28:22 +0000506The only way to perform numeric operations according to the locale is to use the
507special functions defined by this module: :func:`atof`, :func:`atoi`,
508:func:`format`, :func:`str`.
509
Guido van Rossum8d2ef872007-10-15 15:42:31 +0000510There is no way to perform case conversions and character classifications
511according to the locale. For (Unicode) text strings these are done according
512to the character value only, while for byte strings, the conversions and
513classifications are done according to the ASCII value of the byte, and bytes
514whose high bit is set (i.e., non-ASCII bytes) are never converted or considered
515part of a character class such as letter or whitespace.
516
Georg Brandl116aa622007-08-15 14:28:22 +0000517
518.. _embedding-locale:
519
520For extension writers and programs that embed Python
521----------------------------------------------------
522
523Extension modules should never call :func:`setlocale`, except to find out what
524the current locale is. But since the return value can only be used portably to
525restore it, that is not very useful (except perhaps to find out whether or not
526the locale is ``C``).
527
528When Python code uses the :mod:`locale` module to change the locale, this also
529affects the embedding application. If the embedding application doesn't want
530this to happen, it should remove the :mod:`_locale` extension module (which does
531all the work) from the table of built-in modules in the :file:`config.c` file,
532and make sure that the :mod:`_locale` module is not accessible as a shared
533library.
534
535
536.. _locale-gettext:
537
538Access to message catalogs
539--------------------------
540
541The locale module exposes the C library's gettext interface on systems that
542provide this interface. It consists of the functions :func:`gettext`,
543:func:`dgettext`, :func:`dcgettext`, :func:`textdomain`, :func:`bindtextdomain`,
544and :func:`bind_textdomain_codeset`. These are similar to the same functions in
545the :mod:`gettext` module, but use the C library's binary format for message
546catalogs, and the C library's search algorithms for locating message catalogs.
547
548Python applications should normally find no need to invoke these functions, and
549should use :mod:`gettext` instead. A known exception to this rule are
550applications that link use additional C libraries which internally invoke
551:cfunc:`gettext` or :func:`dcgettext`. For these applications, it may be
552necessary to bind the text domain, so that the libraries can properly locate
553their message catalogs.
554