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