localization.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. """
  2. Helpers for configuring locale settings.
  3. Name `localization` is chosen to avoid overlap with builtin `locale` module.
  4. """
  5. from __future__ import annotations
  6. from contextlib import contextmanager
  7. import locale
  8. import platform
  9. import re
  10. import subprocess
  11. from typing import Generator
  12. from pandas._config.config import options
  13. @contextmanager
  14. def set_locale(
  15. new_locale: str | tuple[str, str], lc_var: int = locale.LC_ALL
  16. ) -> Generator[str | tuple[str, str], None, None]:
  17. """
  18. Context manager for temporarily setting a locale.
  19. Parameters
  20. ----------
  21. new_locale : str or tuple
  22. A string of the form <language_country>.<encoding>. For example to set
  23. the current locale to US English with a UTF8 encoding, you would pass
  24. "en_US.UTF-8".
  25. lc_var : int, default `locale.LC_ALL`
  26. The category of the locale being set.
  27. Notes
  28. -----
  29. This is useful when you want to run a particular block of code under a
  30. particular locale, without globally setting the locale. This probably isn't
  31. thread-safe.
  32. """
  33. # getlocale is not always compliant with setlocale, use setlocale. GH#46595
  34. current_locale = locale.setlocale(lc_var)
  35. try:
  36. locale.setlocale(lc_var, new_locale)
  37. normalized_code, normalized_encoding = locale.getlocale()
  38. if normalized_code is not None and normalized_encoding is not None:
  39. yield f"{normalized_code}.{normalized_encoding}"
  40. else:
  41. yield new_locale
  42. finally:
  43. locale.setlocale(lc_var, current_locale)
  44. def can_set_locale(lc: str, lc_var: int = locale.LC_ALL) -> bool:
  45. """
  46. Check to see if we can set a locale, and subsequently get the locale,
  47. without raising an Exception.
  48. Parameters
  49. ----------
  50. lc : str
  51. The locale to attempt to set.
  52. lc_var : int, default `locale.LC_ALL`
  53. The category of the locale being set.
  54. Returns
  55. -------
  56. bool
  57. Whether the passed locale can be set
  58. """
  59. try:
  60. with set_locale(lc, lc_var=lc_var):
  61. pass
  62. except (ValueError, locale.Error):
  63. # horrible name for a Exception subclass
  64. return False
  65. else:
  66. return True
  67. def _valid_locales(locales: list[str] | str, normalize: bool) -> list[str]:
  68. """
  69. Return a list of normalized locales that do not throw an ``Exception``
  70. when set.
  71. Parameters
  72. ----------
  73. locales : str
  74. A string where each locale is separated by a newline.
  75. normalize : bool
  76. Whether to call ``locale.normalize`` on each locale.
  77. Returns
  78. -------
  79. valid_locales : list
  80. A list of valid locales.
  81. """
  82. return [
  83. loc
  84. for loc in (
  85. locale.normalize(loc.strip()) if normalize else loc.strip()
  86. for loc in locales
  87. )
  88. if can_set_locale(loc)
  89. ]
  90. def get_locales(
  91. prefix: str | None = None,
  92. normalize: bool = True,
  93. ) -> list[str]:
  94. """
  95. Get all the locales that are available on the system.
  96. Parameters
  97. ----------
  98. prefix : str
  99. If not ``None`` then return only those locales with the prefix
  100. provided. For example to get all English language locales (those that
  101. start with ``"en"``), pass ``prefix="en"``.
  102. normalize : bool
  103. Call ``locale.normalize`` on the resulting list of available locales.
  104. If ``True``, only locales that can be set without throwing an
  105. ``Exception`` are returned.
  106. Returns
  107. -------
  108. locales : list of strings
  109. A list of locale strings that can be set with ``locale.setlocale()``.
  110. For example::
  111. locale.setlocale(locale.LC_ALL, locale_string)
  112. On error will return an empty list (no locale available, e.g. Windows)
  113. """
  114. if platform.system() in ("Linux", "Darwin"):
  115. raw_locales = subprocess.check_output(["locale", "-a"])
  116. else:
  117. # Other platforms e.g. windows platforms don't define "locale -a"
  118. # Note: is_platform_windows causes circular import here
  119. return []
  120. try:
  121. # raw_locales is "\n" separated list of locales
  122. # it may contain non-decodable parts, so split
  123. # extract what we can and then rejoin.
  124. split_raw_locales = raw_locales.split(b"\n")
  125. out_locales = []
  126. for x in split_raw_locales:
  127. try:
  128. out_locales.append(str(x, encoding=options.display.encoding))
  129. except UnicodeError:
  130. # 'locale -a' is used to populated 'raw_locales' and on
  131. # Redhat 7 Linux (and maybe others) prints locale names
  132. # using windows-1252 encoding. Bug only triggered by
  133. # a few special characters and when there is an
  134. # extensive list of installed locales.
  135. out_locales.append(str(x, encoding="windows-1252"))
  136. except TypeError:
  137. pass
  138. if prefix is None:
  139. return _valid_locales(out_locales, normalize)
  140. pattern = re.compile(f"{prefix}.*")
  141. found = pattern.findall("\n".join(out_locales))
  142. return _valid_locales(found, normalize)