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