blob: 36fbde8ded4018f959285a72a97a1953db688de5 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Petri Lehtinen416ecff2011-11-05 10:18:50 +020026 Exception raised when the locale passed to :func:`setlocale` is not
27 recognized.
Georg Brandl8ec7f652007-08-15 14:28:01 +000028
29
30.. function:: setlocale(category[, locale])
31
Petri Lehtinen416ecff2011-11-05 10:18:50 +020032 If *locale* is given and not ``None``, :func:`setlocale` modifies the locale
33 setting for the *category*. The available categories are listed in the data
34 description below. *locale* may be a string, or an iterable of two strings
35 (language code and encoding). If it's an iterable, it's converted to a locale
36 name using the locale aliasing engine. An empty string specifies the user's
37 default settings. If the modification of the locale fails, the exception
38 :exc:`Error` is raised. If successful, the new locale setting is returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +000039
40 If *locale* is omitted or ``None``, the current setting for *category* is
41 returned.
42
Georg Brandl837fbb02010-11-26 07:58:55 +000043 :func:`setlocale` is not thread-safe on most systems. Applications typically
Georg Brandl8ec7f652007-08-15 14:28:01 +000044 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
Petri Lehtinen416ecff2011-11-05 10:18:50 +020054 Added support for iterable values of the *locale* parameter.
Georg Brandl8ec7f652007-08-15 14:28:01 +000055
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
Georg Brandlb7e14ed2009-07-11 10:51:31 +0000151 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
153 across platforms. The possible argument values are numbers, for which
154 symbolic constants are available in the locale module.
155
156 The :func:`nl_langinfo` function accepts one of the following keys. Most
157 descriptions are taken from the corresponding description in the GNU C
158 library.
159
160 .. data:: CODESET
161
162 Get a string with the name of the character encoding used in the
163 selected locale.
164
165 .. data:: D_T_FMT
166
167 Get a string that can be used as a format string for :func:`strftime` to
Georg Brandl6dea5f52011-03-06 11:09:51 +0100168 represent date and time in a locale-specific way.
Georg Brandlb7e14ed2009-07-11 10:51:31 +0000169
170 .. data:: D_FMT
171
172 Get a string that can be used as a format string for :func:`strftime` to
173 represent a date in a locale-specific way.
174
175 .. data:: T_FMT
176
177 Get a string that can be used as a format string for :func:`strftime` to
178 represent a time in a locale-specific way.
179
180 .. data:: T_FMT_AMPM
181
182 Get a format string for :func:`strftime` to represent time in the am/pm
183 format.
184
185 .. data:: DAY_1 ... DAY_7
186
187 Get the name of the n-th day of the week.
188
189 .. note::
190
191 This follows the US convention of :const:`DAY_1` being Sunday, not the
192 international convention (ISO 8601) that Monday is the first day of the
193 week.
194
195 .. data:: ABDAY_1 ... ABDAY_7
196
197 Get the abbreviated name of the n-th day of the week.
198
199 .. data:: MON_1 ... MON_12
200
201 Get the name of the n-th month.
202
203 .. data:: ABMON_1 ... ABMON_12
204
205 Get the abbreviated name of the n-th month.
206
207 .. data:: RADIXCHAR
208
209 Get the radix character (decimal dot, decimal comma, etc.)
210
211 .. data:: THOUSEP
212
213 Get the separator character for thousands (groups of three digits).
214
215 .. data:: YESEXPR
216
217 Get a regular expression that can be used with the regex function to
218 recognize a positive response to a yes/no question.
219
220 .. note::
221
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100222 The expression is in the syntax suitable for the :c:func:`regex` function
Georg Brandlb7e14ed2009-07-11 10:51:31 +0000223 from the C library, which might differ from the syntax used in :mod:`re`.
224
225 .. data:: NOEXPR
226
227 Get a regular expression that can be used with the regex(3) function to
228 recognize a negative response to a yes/no question.
229
230 .. data:: CRNCYSTR
231
232 Get the currency symbol, preceded by "-" if the symbol should appear before
233 the value, "+" if the symbol should appear after the value, or "." if the
234 symbol should replace the radix character.
235
236 .. data:: ERA
237
238 Get a string that represents the era used in the current locale.
239
240 Most locales do not define this value. An example of a locale which does
241 define this value is the Japanese one. In Japan, the traditional
242 representation of dates includes the name of the era corresponding to the
243 then-emperor's reign.
244
245 Normally it should not be necessary to use this value directly. Specifying
246 the ``E`` modifier in their format strings causes the :func:`strftime`
247 function to use this information. The format of the returned string is not
248 specified, and therefore you should not assume knowledge of it on different
249 systems.
250
Georg Brandlb7e14ed2009-07-11 10:51:31 +0000251 .. data:: ERA_D_T_FMT
252
Georg Brandl6dea5f52011-03-06 11:09:51 +0100253 Get a format string for :func:`strftime` to represent date and time in a
Georg Brandlb7e14ed2009-07-11 10:51:31 +0000254 locale-specific era-based way.
255
256 .. data:: ERA_D_FMT
257
Georg Brandl6dea5f52011-03-06 11:09:51 +0100258 Get a format string for :func:`strftime` to represent a date in a
259 locale-specific era-based way.
260
261 .. data:: ERA_T_FMT
262
263 Get a format string for :func:`strftime` to represent a time in a
Georg Brandlb7e14ed2009-07-11 10:51:31 +0000264 locale-specific era-based way.
265
266 .. data:: ALT_DIGITS
267
268 Get a representation of up to 100 values used to represent the values
269 0 to 99.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000270
271
272.. function:: getdefaultlocale([envvars])
273
274 Tries to determine the default locale settings and returns them as a tuple of
275 the form ``(language code, encoding)``.
276
277 According to POSIX, a program which has not called ``setlocale(LC_ALL, '')``
278 runs using the portable ``'C'`` locale. Calling ``setlocale(LC_ALL, '')`` lets
279 it use the default locale as defined by the :envvar:`LANG` variable. Since we
280 do not want to interfere with the current locale setting we thus emulate the
281 behavior in the way described above.
282
283 To maintain compatibility with other platforms, not only the :envvar:`LANG`
284 variable is tested, but a list of variables given as envvars parameter. The
285 first found to be defined will be used. *envvars* defaults to the search path
286 used in GNU gettext; it must always contain the variable name ``LANG``. The GNU
287 gettext search path contains ``'LANGUAGE'``, ``'LC_ALL'``, ``'LC_CTYPE'``, and
288 ``'LANG'``, in that order.
289
290 Except for the code ``'C'``, the language code corresponds to :rfc:`1766`.
291 *language code* and *encoding* may be ``None`` if their values cannot be
292 determined.
293
294 .. versionadded:: 2.0
295
296
297.. function:: getlocale([category])
298
299 Returns the current setting for the given locale category as sequence containing
300 *language code*, *encoding*. *category* may be one of the :const:`LC_\*` values
301 except :const:`LC_ALL`. It defaults to :const:`LC_CTYPE`.
302
303 Except for the code ``'C'``, the language code corresponds to :rfc:`1766`.
304 *language code* and *encoding* may be ``None`` if their values cannot be
305 determined.
306
307 .. versionadded:: 2.0
308
309
310.. function:: getpreferredencoding([do_setlocale])
311
312 Return the encoding used for text data, according to user preferences. User
313 preferences are expressed differently on different systems, and might not be
314 available programmatically on some systems, so this function only returns a
315 guess.
316
317 On some systems, it is necessary to invoke :func:`setlocale` to obtain the user
318 preferences, so this function is not thread-safe. If invoking setlocale is not
319 necessary or desired, *do_setlocale* should be set to ``False``.
320
321 .. versionadded:: 2.3
322
323
324.. function:: normalize(localename)
325
326 Returns a normalized locale code for the given locale name. The returned locale
327 code is formatted for use with :func:`setlocale`. If normalization fails, the
328 original name is returned unchanged.
329
330 If the given encoding is not known, the function defaults to the default
331 encoding for the locale code just like :func:`setlocale`.
332
333 .. versionadded:: 2.0
334
335
336.. function:: resetlocale([category])
337
338 Sets the locale for *category* to the default setting.
339
340 The default setting is determined by calling :func:`getdefaultlocale`.
341 *category* defaults to :const:`LC_ALL`.
342
343 .. versionadded:: 2.0
344
345
346.. function:: strcoll(string1, string2)
347
348 Compares two strings according to the current :const:`LC_COLLATE` setting. As
349 any other compare function, returns a negative, or a positive value, or ``0``,
350 depending on whether *string1* collates before or after *string2* or is equal to
351 it.
352
353
354.. function:: strxfrm(string)
355
356 .. index:: builtin: cmp
357
358 Transforms a string to one that can be used for the built-in function
359 :func:`cmp`, and still returns locale-aware results. This function can be used
360 when the same string is compared repeatedly, e.g. when collating a sequence of
361 strings.
362
363
364.. function:: format(format, val[, grouping[, monetary]])
365
366 Formats a number *val* according to the current :const:`LC_NUMERIC` setting.
367 The format follows the conventions of the ``%`` operator. For floating point
368 values, the decimal point is modified if appropriate. If *grouping* is true,
369 also takes the grouping into account.
370
371 If *monetary* is true, the conversion uses monetary thousands separator and
372 grouping strings.
373
374 Please note that this function will only work for exactly one %char specifier.
375 For whole format strings, use :func:`format_string`.
376
377 .. versionchanged:: 2.5
378 Added the *monetary* parameter.
379
380
381.. function:: format_string(format, val[, grouping])
382
383 Processes formatting specifiers as in ``format % val``, but takes the current
384 locale settings into account.
385
386 .. versionadded:: 2.5
387
388
389.. function:: currency(val[, symbol[, grouping[, international]]])
390
391 Formats a number *val* according to the current :const:`LC_MONETARY` settings.
392
393 The returned string includes the currency symbol if *symbol* is true, which is
394 the default. If *grouping* is true (which is not the default), grouping is done
395 with the value. If *international* is true (which is not the default), the
396 international currency symbol is used.
397
398 Note that this function will not work with the 'C' locale, so you have to set a
399 locale via :func:`setlocale` first.
400
401 .. versionadded:: 2.5
402
403
404.. function:: str(float)
405
406 Formats a floating point number using the same format as the built-in function
407 ``str(float)``, but takes the decimal point into account.
408
409
410.. function:: atof(string)
411
412 Converts a string to a floating point number, following the :const:`LC_NUMERIC`
413 settings.
414
415
416.. function:: atoi(string)
417
418 Converts a string to an integer, following the :const:`LC_NUMERIC` conventions.
419
420
421.. data:: LC_CTYPE
422
423 .. index:: module: string
424
425 Locale category for the character type functions. Depending on the settings of
426 this category, the functions of module :mod:`string` dealing with case change
427 their behaviour.
428
429
430.. data:: LC_COLLATE
431
432 Locale category for sorting strings. The functions :func:`strcoll` and
433 :func:`strxfrm` of the :mod:`locale` module are affected.
434
435
436.. data:: LC_TIME
437
438 Locale category for the formatting of time. The function :func:`time.strftime`
439 follows these conventions.
440
441
442.. data:: LC_MONETARY
443
444 Locale category for formatting of monetary values. The available options are
445 available from the :func:`localeconv` function.
446
447
448.. data:: LC_MESSAGES
449
450 Locale category for message display. Python currently does not support
451 application specific locale-aware messages. Messages displayed by the operating
452 system, like those returned by :func:`os.strerror` might be affected by this
453 category.
454
455
456.. data:: LC_NUMERIC
457
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000458 Locale category for formatting numbers. The functions :func:`.format`,
459 :func:`atoi`, :func:`atof` and :func:`.str` of the :mod:`locale` module are
Georg Brandl8ec7f652007-08-15 14:28:01 +0000460 affected by that category. All other numeric formatting operations are not
461 affected.
462
463
464.. data:: LC_ALL
465
466 Combination of all locale settings. If this flag is used when the locale is
467 changed, setting the locale for all categories is attempted. If that fails for
468 any category, no category is changed at all. When the locale is retrieved using
469 this flag, a string indicating the setting for all categories is returned. This
470 string can be later used to restore the settings.
471
472
473.. data:: CHAR_MAX
474
475 This is a symbolic constant used for different values returned by
476 :func:`localeconv`.
477
Georg Brandl8ec7f652007-08-15 14:28:01 +0000478
479Example::
480
481 >>> import locale
Georg Brandlee1a7da2008-11-15 08:10:04 +0000482 >>> loc = locale.getlocale() # get current locale
Georg Brandlb7e14ed2009-07-11 10:51:31 +0000483 # use German locale; name might vary with platform
484 >>> locale.setlocale(locale.LC_ALL, 'de_DE')
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000485 >>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut
Georg Brandl8ec7f652007-08-15 14:28:01 +0000486 >>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale
487 >>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale
488 >>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale
489
490
491Background, details, hints, tips and caveats
492--------------------------------------------
493
494The C standard defines the locale as a program-wide property that may be
495relatively expensive to change. On top of that, some implementation are broken
496in such a way that frequent locale changes may cause core dumps. This makes the
497locale somewhat painful to use correctly.
498
499Initially, when a program is started, the locale is the ``C`` locale, no matter
500what the user's preferred locale is. The program must explicitly say that it
501wants the user's preferred locale settings by calling ``setlocale(LC_ALL, '')``.
502
503It is generally a bad idea to call :func:`setlocale` in some library routine,
504since as a side effect it affects the entire program. Saving and restoring it
505is almost as bad: it is expensive and affects other threads that happen to run
506before the settings have been restored.
507
508If, when coding a module for general use, you need a locale independent version
509of an operation that is affected by the locale (such as :func:`string.lower`, or
510certain formats used with :func:`time.strftime`), you will have to find a way to
511do it without using the standard library routine. Even better is convincing
512yourself that using locale settings is okay. Only as a last resort should you
513document that your module is not compatible with non-\ ``C`` locale settings.
514
515.. index:: module: string
516
517The case conversion functions in the :mod:`string` module are affected by the
518locale settings. When a call to the :func:`setlocale` function changes the
519:const:`LC_CTYPE` settings, the variables ``string.lowercase``,
520``string.uppercase`` and ``string.letters`` are recalculated. Note that code
521that uses these variable through ':keyword:`from` ... :keyword:`import` ...',
522e.g. ``from string import letters``, is not affected by subsequent
523:func:`setlocale` calls.
524
525The only way to perform numeric operations according to the locale is to use the
526special functions defined by this module: :func:`atof`, :func:`atoi`,
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000527:func:`.format`, :func:`.str`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000528
529
530.. _embedding-locale:
531
532For extension writers and programs that embed Python
533----------------------------------------------------
534
535Extension modules should never call :func:`setlocale`, except to find out what
536the current locale is. But since the return value can only be used portably to
537restore it, that is not very useful (except perhaps to find out whether or not
538the locale is ``C``).
539
540When Python code uses the :mod:`locale` module to change the locale, this also
541affects the embedding application. If the embedding application doesn't want
542this to happen, it should remove the :mod:`_locale` extension module (which does
543all the work) from the table of built-in modules in the :file:`config.c` file,
544and make sure that the :mod:`_locale` module is not accessible as a shared
545library.
546
547
548.. _locale-gettext:
549
550Access to message catalogs
551--------------------------
552
553The locale module exposes the C library's gettext interface on systems that
554provide this interface. It consists of the functions :func:`gettext`,
555:func:`dgettext`, :func:`dcgettext`, :func:`textdomain`, :func:`bindtextdomain`,
556and :func:`bind_textdomain_codeset`. These are similar to the same functions in
557the :mod:`gettext` module, but use the C library's binary format for message
558catalogs, and the C library's search algorithms for locating message catalogs.
559
560Python applications should normally find no need to invoke these functions, and
561should use :mod:`gettext` instead. A known exception to this rule are
Georg Brandl3b85b9b2010-11-26 08:20:18 +0000562applications that link with additional C libraries which internally invoke
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100563:c:func:`gettext` or :func:`dcgettext`. For these applications, it may be
Georg Brandl8ec7f652007-08-15 14:28:01 +0000564necessary to bind the text domain, so that the libraries can properly locate
565their message catalogs.
566