/Doc/library/locale.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 578 lines · 380 code · 198 blank · 0 comment · 0 complexity · d98cb5f539a00ceeca5e24c3657e6e72 MD5 · raw file

  1. :mod:`locale` --- Internationalization services
  2. ===============================================
  3. .. module:: locale
  4. :synopsis: Internationalization services.
  5. .. moduleauthor:: Martin von Lรถwis <martin@v.loewis.de>
  6. .. sectionauthor:: Martin von Lรถwis <martin@v.loewis.de>
  7. The :mod:`locale` module opens access to the POSIX locale database and
  8. functionality. The POSIX locale mechanism allows programmers to deal with
  9. certain cultural issues in an application, without requiring the programmer to
  10. know all the specifics of each country where the software is executed.
  11. .. index:: module: _locale
  12. The :mod:`locale` module is implemented on top of the :mod:`_locale` module,
  13. which in turn uses an ANSI C locale implementation if available.
  14. The :mod:`locale` module defines the following exception and functions:
  15. .. exception:: Error
  16. Exception raised when :func:`setlocale` fails.
  17. .. function:: setlocale(category[, locale])
  18. If *locale* is specified, it may be a string, a tuple of the form ``(language
  19. code, encoding)``, or ``None``. If it is a tuple, it is converted to a string
  20. using the locale aliasing engine. If *locale* is given and not ``None``,
  21. :func:`setlocale` modifies the locale setting for the *category*. The available
  22. categories are listed in the data description below. The value is the name of a
  23. locale. An empty string specifies the user's default settings. If the
  24. modification of the locale fails, the exception :exc:`Error` is raised. If
  25. successful, the new locale setting is returned.
  26. If *locale* is omitted or ``None``, the current setting for *category* is
  27. returned.
  28. :func:`setlocale` is not thread safe on most systems. Applications typically
  29. start with a call of ::
  30. import locale
  31. locale.setlocale(locale.LC_ALL, '')
  32. This sets the locale for all categories to the user's default setting (typically
  33. specified in the :envvar:`LANG` environment variable). If the locale is not
  34. changed thereafter, using multithreading should not cause problems.
  35. .. versionchanged:: 2.0
  36. Added support for tuple values of the *locale* parameter.
  37. .. function:: localeconv()
  38. Returns the database of the local conventions as a dictionary. This dictionary
  39. has the following strings as keys:
  40. +----------------------+-------------------------------------+--------------------------------+
  41. | Category | Key | Meaning |
  42. +======================+=====================================+================================+
  43. | :const:`LC_NUMERIC` | ``'decimal_point'`` | Decimal point character. |
  44. +----------------------+-------------------------------------+--------------------------------+
  45. | | ``'grouping'`` | Sequence of numbers specifying |
  46. | | | which relative positions the |
  47. | | | ``'thousands_sep'`` is |
  48. | | | expected. If the sequence is |
  49. | | | terminated with |
  50. | | | :const:`CHAR_MAX`, no further |
  51. | | | grouping is performed. If the |
  52. | | | sequence terminates with a |
  53. | | | ``0``, the last group size is |
  54. | | | repeatedly used. |
  55. +----------------------+-------------------------------------+--------------------------------+
  56. | | ``'thousands_sep'`` | Character used between groups. |
  57. +----------------------+-------------------------------------+--------------------------------+
  58. | :const:`LC_MONETARY` | ``'int_curr_symbol'`` | International currency symbol. |
  59. +----------------------+-------------------------------------+--------------------------------+
  60. | | ``'currency_symbol'`` | Local currency symbol. |
  61. +----------------------+-------------------------------------+--------------------------------+
  62. | | ``'p_cs_precedes/n_cs_precedes'`` | Whether the currency symbol |
  63. | | | precedes the value (for |
  64. | | | positive resp. negative |
  65. | | | values). |
  66. +----------------------+-------------------------------------+--------------------------------+
  67. | | ``'p_sep_by_space/n_sep_by_space'`` | Whether the currency symbol is |
  68. | | | separated from the value by a |
  69. | | | space (for positive resp. |
  70. | | | negative values). |
  71. +----------------------+-------------------------------------+--------------------------------+
  72. | | ``'mon_decimal_point'`` | Decimal point used for |
  73. | | | monetary values. |
  74. +----------------------+-------------------------------------+--------------------------------+
  75. | | ``'frac_digits'`` | Number of fractional digits |
  76. | | | used in local formatting of |
  77. | | | monetary values. |
  78. +----------------------+-------------------------------------+--------------------------------+
  79. | | ``'int_frac_digits'`` | Number of fractional digits |
  80. | | | used in international |
  81. | | | formatting of monetary values. |
  82. +----------------------+-------------------------------------+--------------------------------+
  83. | | ``'mon_thousands_sep'`` | Group separator used for |
  84. | | | monetary values. |
  85. +----------------------+-------------------------------------+--------------------------------+
  86. | | ``'mon_grouping'`` | Equivalent to ``'grouping'``, |
  87. | | | used for monetary values. |
  88. +----------------------+-------------------------------------+--------------------------------+
  89. | | ``'positive_sign'`` | Symbol used to annotate a |
  90. | | | positive monetary value. |
  91. +----------------------+-------------------------------------+--------------------------------+
  92. | | ``'negative_sign'`` | Symbol used to annotate a |
  93. | | | negative monetary value. |
  94. +----------------------+-------------------------------------+--------------------------------+
  95. | | ``'p_sign_posn/n_sign_posn'`` | The position of the sign (for |
  96. | | | positive resp. negative |
  97. | | | values), see below. |
  98. +----------------------+-------------------------------------+--------------------------------+
  99. All numeric values can be set to :const:`CHAR_MAX` to indicate that there is no
  100. value specified in this locale.
  101. The possible values for ``'p_sign_posn'`` and ``'n_sign_posn'`` are given below.
  102. +--------------+-----------------------------------------+
  103. | Value | Explanation |
  104. +==============+=========================================+
  105. | ``0`` | Currency and value are surrounded by |
  106. | | parentheses. |
  107. +--------------+-----------------------------------------+
  108. | ``1`` | The sign should precede the value and |
  109. | | currency symbol. |
  110. +--------------+-----------------------------------------+
  111. | ``2`` | The sign should follow the value and |
  112. | | currency symbol. |
  113. +--------------+-----------------------------------------+
  114. | ``3`` | The sign should immediately precede the |
  115. | | value. |
  116. +--------------+-----------------------------------------+
  117. | ``4`` | The sign should immediately follow the |
  118. | | value. |
  119. +--------------+-----------------------------------------+
  120. | ``CHAR_MAX`` | Nothing is specified in this locale. |
  121. +--------------+-----------------------------------------+
  122. .. function:: nl_langinfo(option)
  123. Return some locale-specific information as a string. This function is not
  124. available on all systems, and the set of possible options might also vary across
  125. platforms. The possible argument values are numbers, for which symbolic
  126. constants are available in the locale module.
  127. .. function:: getdefaultlocale([envvars])
  128. Tries to determine the default locale settings and returns them as a tuple of
  129. the form ``(language code, encoding)``.
  130. According to POSIX, a program which has not called ``setlocale(LC_ALL, '')``
  131. runs using the portable ``'C'`` locale. Calling ``setlocale(LC_ALL, '')`` lets
  132. it use the default locale as defined by the :envvar:`LANG` variable. Since we
  133. do not want to interfere with the current locale setting we thus emulate the
  134. behavior in the way described above.
  135. To maintain compatibility with other platforms, not only the :envvar:`LANG`
  136. variable is tested, but a list of variables given as envvars parameter. The
  137. first found to be defined will be used. *envvars* defaults to the search path
  138. used in GNU gettext; it must always contain the variable name ``LANG``. The GNU
  139. gettext search path contains ``'LANGUAGE'``, ``'LC_ALL'``, ``'LC_CTYPE'``, and
  140. ``'LANG'``, in that order.
  141. Except for the code ``'C'``, the language code corresponds to :rfc:`1766`.
  142. *language code* and *encoding* may be ``None`` if their values cannot be
  143. determined.
  144. .. versionadded:: 2.0
  145. .. function:: getlocale([category])
  146. Returns the current setting for the given locale category as sequence containing
  147. *language code*, *encoding*. *category* may be one of the :const:`LC_\*` values
  148. except :const:`LC_ALL`. It defaults to :const:`LC_CTYPE`.
  149. Except for the code ``'C'``, the language code corresponds to :rfc:`1766`.
  150. *language code* and *encoding* may be ``None`` if their values cannot be
  151. determined.
  152. .. versionadded:: 2.0
  153. .. function:: getpreferredencoding([do_setlocale])
  154. Return the encoding used for text data, according to user preferences. User
  155. preferences are expressed differently on different systems, and might not be
  156. available programmatically on some systems, so this function only returns a
  157. guess.
  158. On some systems, it is necessary to invoke :func:`setlocale` to obtain the user
  159. preferences, so this function is not thread-safe. If invoking setlocale is not
  160. necessary or desired, *do_setlocale* should be set to ``False``.
  161. .. versionadded:: 2.3
  162. .. function:: normalize(localename)
  163. Returns a normalized locale code for the given locale name. The returned locale
  164. code is formatted for use with :func:`setlocale`. If normalization fails, the
  165. original name is returned unchanged.
  166. If the given encoding is not known, the function defaults to the default
  167. encoding for the locale code just like :func:`setlocale`.
  168. .. versionadded:: 2.0
  169. .. function:: resetlocale([category])
  170. Sets the locale for *category* to the default setting.
  171. The default setting is determined by calling :func:`getdefaultlocale`.
  172. *category* defaults to :const:`LC_ALL`.
  173. .. versionadded:: 2.0
  174. .. function:: strcoll(string1, string2)
  175. Compares two strings according to the current :const:`LC_COLLATE` setting. As
  176. any other compare function, returns a negative, or a positive value, or ``0``,
  177. depending on whether *string1* collates before or after *string2* or is equal to
  178. it.
  179. .. function:: strxfrm(string)
  180. .. index:: builtin: cmp
  181. Transforms a string to one that can be used for the built-in function
  182. :func:`cmp`, and still returns locale-aware results. This function can be used
  183. when the same string is compared repeatedly, e.g. when collating a sequence of
  184. strings.
  185. .. function:: format(format, val[, grouping[, monetary]])
  186. Formats a number *val* according to the current :const:`LC_NUMERIC` setting.
  187. The format follows the conventions of the ``%`` operator. For floating point
  188. values, the decimal point is modified if appropriate. If *grouping* is true,
  189. also takes the grouping into account.
  190. If *monetary* is true, the conversion uses monetary thousands separator and
  191. grouping strings.
  192. Please note that this function will only work for exactly one %char specifier.
  193. For whole format strings, use :func:`format_string`.
  194. .. versionchanged:: 2.5
  195. Added the *monetary* parameter.
  196. .. function:: format_string(format, val[, grouping])
  197. Processes formatting specifiers as in ``format % val``, but takes the current
  198. locale settings into account.
  199. .. versionadded:: 2.5
  200. .. function:: currency(val[, symbol[, grouping[, international]]])
  201. Formats a number *val* according to the current :const:`LC_MONETARY` settings.
  202. The returned string includes the currency symbol if *symbol* is true, which is
  203. the default. If *grouping* is true (which is not the default), grouping is done
  204. with the value. If *international* is true (which is not the default), the
  205. international currency symbol is used.
  206. Note that this function will not work with the 'C' locale, so you have to set a
  207. locale via :func:`setlocale` first.
  208. .. versionadded:: 2.5
  209. .. function:: str(float)
  210. Formats a floating point number using the same format as the built-in function
  211. ``str(float)``, but takes the decimal point into account.
  212. .. function:: atof(string)
  213. Converts a string to a floating point number, following the :const:`LC_NUMERIC`
  214. settings.
  215. .. function:: atoi(string)
  216. Converts a string to an integer, following the :const:`LC_NUMERIC` conventions.
  217. .. data:: LC_CTYPE
  218. .. index:: module: string
  219. Locale category for the character type functions. Depending on the settings of
  220. this category, the functions of module :mod:`string` dealing with case change
  221. their behaviour.
  222. .. data:: LC_COLLATE
  223. Locale category for sorting strings. The functions :func:`strcoll` and
  224. :func:`strxfrm` of the :mod:`locale` module are affected.
  225. .. data:: LC_TIME
  226. Locale category for the formatting of time. The function :func:`time.strftime`
  227. follows these conventions.
  228. .. data:: LC_MONETARY
  229. Locale category for formatting of monetary values. The available options are
  230. available from the :func:`localeconv` function.
  231. .. data:: LC_MESSAGES
  232. Locale category for message display. Python currently does not support
  233. application specific locale-aware messages. Messages displayed by the operating
  234. system, like those returned by :func:`os.strerror` might be affected by this
  235. category.
  236. .. data:: LC_NUMERIC
  237. Locale category for formatting numbers. The functions :func:`format`,
  238. :func:`atoi`, :func:`atof` and :func:`str` of the :mod:`locale` module are
  239. affected by that category. All other numeric formatting operations are not
  240. affected.
  241. .. data:: LC_ALL
  242. Combination of all locale settings. If this flag is used when the locale is
  243. changed, setting the locale for all categories is attempted. If that fails for
  244. any category, no category is changed at all. When the locale is retrieved using
  245. this flag, a string indicating the setting for all categories is returned. This
  246. string can be later used to restore the settings.
  247. .. data:: CHAR_MAX
  248. This is a symbolic constant used for different values returned by
  249. :func:`localeconv`.
  250. The :func:`nl_langinfo` function accepts one of the following keys. Most
  251. descriptions are taken from the corresponding description in the GNU C library.
  252. .. data:: CODESET
  253. Return a string with the name of the character encoding used in the selected
  254. locale.
  255. .. data:: D_T_FMT
  256. Return a string that can be used as a format string for strftime(3) to represent
  257. time and date in a locale-specific way.
  258. .. data:: D_FMT
  259. Return a string that can be used as a format string for strftime(3) to represent
  260. a date in a locale-specific way.
  261. .. data:: T_FMT
  262. Return a string that can be used as a format string for strftime(3) to represent
  263. a time in a locale-specific way.
  264. .. data:: T_FMT_AMPM
  265. The return value can be used as a format string for 'strftime' to represent time
  266. in the am/pm format.
  267. .. data:: DAY_1 ... DAY_7
  268. Return name of the n-th day of the week.
  269. .. note::
  270. This follows the US convention of :const:`DAY_1` being Sunday, not the
  271. international convention (ISO 8601) that Monday is the first day of the week.
  272. .. data:: ABDAY_1 ... ABDAY_7
  273. Return abbreviated name of the n-th day of the week.
  274. .. data:: MON_1 ... MON_12
  275. Return name of the n-th month.
  276. .. data:: ABMON_1 ... ABMON_12
  277. Return abbreviated name of the n-th month.
  278. .. data:: RADIXCHAR
  279. Return radix character (decimal dot, decimal comma, etc.)
  280. .. data:: THOUSEP
  281. Return separator character for thousands (groups of three digits).
  282. .. data:: YESEXPR
  283. Return a regular expression that can be used with the regex function to
  284. recognize a positive response to a yes/no question.
  285. .. note::
  286. The expression is in the syntax suitable for the :cfunc:`regex` function from
  287. the C library, which might differ from the syntax used in :mod:`re`.
  288. .. data:: NOEXPR
  289. Return a regular expression that can be used with the regex(3) function to
  290. recognize a negative response to a yes/no question.
  291. .. data:: CRNCYSTR
  292. Return the currency symbol, preceded by "-" if the symbol should appear before
  293. the value, "+" if the symbol should appear after the value, or "." if the symbol
  294. should replace the radix character.
  295. .. data:: ERA
  296. The return value represents the era used in the current locale.
  297. Most locales do not define this value. An example of a locale which does define
  298. this value is the Japanese one. In Japan, the traditional representation of
  299. dates includes the name of the era corresponding to the then-emperor's reign.
  300. Normally it should not be necessary to use this value directly. Specifying the
  301. ``E`` modifier in their format strings causes the :func:`strftime` function to
  302. use this information. The format of the returned string is not specified, and
  303. therefore you should not assume knowledge of it on different systems.
  304. .. data:: ERA_YEAR
  305. The return value gives the year in the relevant era of the locale.
  306. .. data:: ERA_D_T_FMT
  307. This return value can be used as a format string for :func:`strftime` to
  308. represent dates and times in a locale-specific era-based way.
  309. .. data:: ERA_D_FMT
  310. This return value can be used as a format string for :func:`strftime` to
  311. represent time in a locale-specific era-based way.
  312. .. data:: ALT_DIGITS
  313. The return value is a representation of up to 100 values used to represent the
  314. values 0 to 99.
  315. Example::
  316. >>> import locale
  317. >>> loc = locale.getlocale() # get current locale
  318. >>> locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform
  319. >>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut
  320. >>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale
  321. >>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale
  322. >>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale
  323. Background, details, hints, tips and caveats
  324. --------------------------------------------
  325. The C standard defines the locale as a program-wide property that may be
  326. relatively expensive to change. On top of that, some implementation are broken
  327. in such a way that frequent locale changes may cause core dumps. This makes the
  328. locale somewhat painful to use correctly.
  329. Initially, when a program is started, the locale is the ``C`` locale, no matter
  330. what the user's preferred locale is. The program must explicitly say that it
  331. wants the user's preferred locale settings by calling ``setlocale(LC_ALL, '')``.
  332. It is generally a bad idea to call :func:`setlocale` in some library routine,
  333. since as a side effect it affects the entire program. Saving and restoring it
  334. is almost as bad: it is expensive and affects other threads that happen to run
  335. before the settings have been restored.
  336. If, when coding a module for general use, you need a locale independent version
  337. of an operation that is affected by the locale (such as :func:`string.lower`, or
  338. certain formats used with :func:`time.strftime`), you will have to find a way to
  339. do it without using the standard library routine. Even better is convincing
  340. yourself that using locale settings is okay. Only as a last resort should you
  341. document that your module is not compatible with non-\ ``C`` locale settings.
  342. .. index:: module: string
  343. The case conversion functions in the :mod:`string` module are affected by the
  344. locale settings. When a call to the :func:`setlocale` function changes the
  345. :const:`LC_CTYPE` settings, the variables ``string.lowercase``,
  346. ``string.uppercase`` and ``string.letters`` are recalculated. Note that code
  347. that uses these variable through ':keyword:`from` ... :keyword:`import` ...',
  348. e.g. ``from string import letters``, is not affected by subsequent
  349. :func:`setlocale` calls.
  350. The only way to perform numeric operations according to the locale is to use the
  351. special functions defined by this module: :func:`atof`, :func:`atoi`,
  352. :func:`format`, :func:`str`.
  353. .. _embedding-locale:
  354. For extension writers and programs that embed Python
  355. ----------------------------------------------------
  356. Extension modules should never call :func:`setlocale`, except to find out what
  357. the current locale is. But since the return value can only be used portably to
  358. restore it, that is not very useful (except perhaps to find out whether or not
  359. the locale is ``C``).
  360. When Python code uses the :mod:`locale` module to change the locale, this also
  361. affects the embedding application. If the embedding application doesn't want
  362. this to happen, it should remove the :mod:`_locale` extension module (which does
  363. all the work) from the table of built-in modules in the :file:`config.c` file,
  364. and make sure that the :mod:`_locale` module is not accessible as a shared
  365. library.
  366. .. _locale-gettext:
  367. Access to message catalogs
  368. --------------------------
  369. The locale module exposes the C library's gettext interface on systems that
  370. provide this interface. It consists of the functions :func:`gettext`,
  371. :func:`dgettext`, :func:`dcgettext`, :func:`textdomain`, :func:`bindtextdomain`,
  372. and :func:`bind_textdomain_codeset`. These are similar to the same functions in
  373. the :mod:`gettext` module, but use the C library's binary format for message
  374. catalogs, and the C library's search algorithms for locating message catalogs.
  375. Python applications should normally find no need to invoke these functions, and
  376. should use :mod:`gettext` instead. A known exception to this rule are
  377. applications that link use additional C libraries which internally invoke
  378. :cfunc:`gettext` or :func:`dcgettext`. For these applications, it may be
  379. necessary to bind the text domain, so that the libraries can properly locate
  380. their message catalogs.