Debian Codegraph @

Doc/library/locale.rst

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