core.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. """
  2. babel.core
  3. ~~~~~~~~~~
  4. Core locale representation and locale data access.
  5. :copyright: (c) 2013-2026 by the Babel Team.
  6. :license: BSD, see LICENSE for more details.
  7. """
  8. from __future__ import annotations
  9. import os
  10. import pickle
  11. from collections.abc import Iterable, Mapping
  12. from typing import TYPE_CHECKING, Any, Literal
  13. from babel import localedata
  14. from babel.plural import PluralRule
  15. __all__ = [
  16. 'Locale',
  17. 'UnknownLocaleError',
  18. 'default_locale',
  19. 'get_cldr_version',
  20. 'get_global',
  21. 'get_locale_identifier',
  22. 'negotiate_locale',
  23. 'parse_locale',
  24. ]
  25. if TYPE_CHECKING:
  26. from typing_extensions import TypeAlias
  27. _GLOBAL_KEY: TypeAlias = Literal[
  28. "all_currencies",
  29. "cldr",
  30. "currency_fractions",
  31. "language_aliases",
  32. "likely_subtags",
  33. "meta_zones",
  34. "parent_exceptions",
  35. "script_aliases",
  36. "territory_aliases",
  37. "territory_currencies",
  38. "territory_languages",
  39. "territory_zones",
  40. "variant_aliases",
  41. "windows_zone_mapping",
  42. "zone_aliases",
  43. "zone_territories",
  44. ]
  45. _global_data: Mapping[_GLOBAL_KEY, Mapping[str, Any]] | None
  46. _global_data = None
  47. _default_plural_rule = PluralRule({})
  48. def _raise_no_data_error():
  49. raise RuntimeError(
  50. 'The babel data files are not available. '
  51. 'This usually happens because you are using '
  52. 'a source checkout from Babel and you did '
  53. 'not build the data files. Just make sure '
  54. 'to run "python setup.py import_cldr" before '
  55. 'installing the library.',
  56. )
  57. def get_global(key: _GLOBAL_KEY) -> Mapping[str, Any]:
  58. """Return the dictionary for the given key in the global data.
  59. The global data is stored in the ``babel/global.dat`` file and contains
  60. information independent of individual locales.
  61. >>> get_global('zone_aliases')['UTC']
  62. 'Etc/UTC'
  63. >>> get_global('zone_territories')['Europe/Berlin']
  64. 'DE'
  65. The keys available are:
  66. - ``all_currencies``
  67. - ``cldr`` (metadata)
  68. - ``currency_fractions``
  69. - ``language_aliases``
  70. - ``likely_subtags``
  71. - ``parent_exceptions``
  72. - ``script_aliases``
  73. - ``territory_aliases``
  74. - ``territory_currencies``
  75. - ``territory_languages``
  76. - ``territory_zones``
  77. - ``variant_aliases``
  78. - ``windows_zone_mapping``
  79. - ``zone_aliases``
  80. - ``zone_territories``
  81. .. note:: The internal structure of the data may change between versions.
  82. .. versionadded:: 0.9
  83. :param key: the data key
  84. """
  85. global _global_data
  86. if _global_data is None:
  87. dirname = os.path.join(os.path.dirname(__file__))
  88. filename = os.path.join(dirname, 'global.dat')
  89. if not os.path.isfile(filename):
  90. _raise_no_data_error()
  91. with open(filename, 'rb') as fileobj:
  92. _global_data = pickle.load(fileobj)
  93. assert _global_data is not None
  94. return _global_data.get(key, {})
  95. LOCALE_ALIASES = {
  96. 'ar': 'ar_SY', 'bg': 'bg_BG', 'bs': 'bs_BA', 'ca': 'ca_ES', 'cs': 'cs_CZ',
  97. 'da': 'da_DK', 'de': 'de_DE', 'el': 'el_GR', 'en': 'en_US', 'es': 'es_ES',
  98. 'et': 'et_EE', 'fa': 'fa_IR', 'fi': 'fi_FI', 'fr': 'fr_FR', 'gl': 'gl_ES',
  99. 'he': 'he_IL', 'hu': 'hu_HU', 'id': 'id_ID', 'is': 'is_IS', 'it': 'it_IT',
  100. 'ja': 'ja_JP', 'km': 'km_KH', 'ko': 'ko_KR', 'lt': 'lt_LT', 'lv': 'lv_LV',
  101. 'mk': 'mk_MK', 'nl': 'nl_NL', 'nn': 'nn_NO', 'no': 'nb_NO', 'pl': 'pl_PL',
  102. 'pt': 'pt_PT', 'ro': 'ro_RO', 'ru': 'ru_RU', 'sk': 'sk_SK', 'sl': 'sl_SI',
  103. 'sv': 'sv_SE', 'th': 'th_TH', 'tr': 'tr_TR', 'uk': 'uk_UA',
  104. } # fmt: skip
  105. class UnknownLocaleError(Exception):
  106. """Exception thrown when a locale is requested for which no locale data
  107. is available.
  108. """
  109. def __init__(self, identifier: str) -> None:
  110. """Create the exception.
  111. :param identifier: the identifier string of the unsupported locale
  112. """
  113. Exception.__init__(self, f"unknown locale {identifier!r}")
  114. #: The identifier of the locale that could not be found.
  115. self.identifier = identifier
  116. class Locale:
  117. """Representation of a specific locale.
  118. >>> locale = Locale('en', 'US')
  119. >>> repr(locale)
  120. "Locale('en', territory='US')"
  121. >>> locale.display_name
  122. 'English (United States)'
  123. A `Locale` object can also be instantiated from a raw locale string:
  124. >>> locale = Locale.parse('en-US', sep='-')
  125. >>> repr(locale)
  126. "Locale('en', territory='US')"
  127. `Locale` objects provide access to a collection of locale data, such as
  128. territory and language names, number and date format patterns, and more:
  129. >>> locale.number_symbols['latn']['decimal']
  130. '.'
  131. If a locale is requested for which no locale data is available, an
  132. `UnknownLocaleError` is raised:
  133. >>> Locale.parse('en_XX')
  134. Traceback (most recent call last):
  135. ...
  136. UnknownLocaleError: unknown locale 'en_XX'
  137. For more information see :rfc:`3066`.
  138. """
  139. def __init__(
  140. self,
  141. language: str,
  142. territory: str | None = None,
  143. script: str | None = None,
  144. variant: str | None = None,
  145. modifier: str | None = None,
  146. ) -> None:
  147. """Initialize the locale object from the given identifier components.
  148. >>> locale = Locale('en', 'US')
  149. >>> locale.language
  150. 'en'
  151. >>> locale.territory
  152. 'US'
  153. :param language: the language code
  154. :param territory: the territory (country or region) code
  155. :param script: the script code
  156. :param variant: the variant code
  157. :param modifier: a modifier (following the '@' symbol, sometimes called '@variant')
  158. :raise `UnknownLocaleError`: if no locale data is available for the
  159. requested locale
  160. """
  161. #: the language code
  162. self.language = language
  163. #: the territory (country or region) code
  164. self.territory = territory
  165. #: the script code
  166. self.script = script
  167. #: the variant code
  168. self.variant = variant
  169. #: the modifier
  170. self.modifier = modifier
  171. self.__data: localedata.LocaleDataDict | None = None
  172. identifier = str(self)
  173. identifier_without_modifier = identifier.partition('@')[0]
  174. if localedata.exists(identifier):
  175. self.__data_identifier = identifier
  176. elif localedata.exists(identifier_without_modifier):
  177. self.__data_identifier = identifier_without_modifier
  178. else:
  179. raise UnknownLocaleError(identifier)
  180. @classmethod
  181. def default(
  182. cls,
  183. category: str | None = None,
  184. aliases: Mapping[str, str] = LOCALE_ALIASES,
  185. ) -> Locale:
  186. """Return the system default locale for the specified category.
  187. >>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LC_MESSAGES']:
  188. ... os.environ[name] = ''
  189. >>> os.environ['LANG'] = 'fr_FR.UTF-8'
  190. >>> Locale.default('LC_MESSAGES')
  191. Locale('fr', territory='FR')
  192. The following fallbacks to the variable are always considered:
  193. - ``LANGUAGE``
  194. - ``LC_ALL``
  195. - ``LC_CTYPE``
  196. - ``LANG``
  197. :param category: one of the ``LC_XXX`` environment variable names
  198. :param aliases: a dictionary of aliases for locale identifiers
  199. """
  200. # XXX: use likely subtag expansion here instead of the
  201. # aliases dictionary.
  202. locale_string = default_locale(category, aliases=aliases)
  203. return cls.parse(locale_string)
  204. @classmethod
  205. def negotiate(
  206. cls,
  207. preferred: Iterable[str],
  208. available: Iterable[str],
  209. sep: str = '_',
  210. aliases: Mapping[str, str] = LOCALE_ALIASES,
  211. ) -> Locale | None:
  212. """Find the best match between available and requested locale strings.
  213. >>> Locale.negotiate(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
  214. Locale('de', territory='DE')
  215. >>> Locale.negotiate(['de_DE', 'en_US'], ['en', 'de'])
  216. Locale('de')
  217. >>> Locale.negotiate(['de_DE', 'de'], ['en_US'])
  218. You can specify the character used in the locale identifiers to separate
  219. the different components. This separator is applied to both lists. Also,
  220. case is ignored in the comparison:
  221. >>> Locale.negotiate(['de-DE', 'de'], ['en-us', 'de-de'], sep='-')
  222. Locale('de', territory='DE')
  223. :param preferred: the list of locale identifiers preferred by the user
  224. :param available: the list of locale identifiers available
  225. :param aliases: a dictionary of aliases for locale identifiers
  226. :param sep: separator for parsing; e.g. Windows tends to use '-' instead of '_'.
  227. """
  228. identifier = negotiate_locale(preferred, available, sep=sep, aliases=aliases)
  229. if identifier:
  230. return Locale.parse(identifier, sep=sep)
  231. return None
  232. @classmethod
  233. def parse(
  234. cls,
  235. identifier: Locale | str | None,
  236. sep: str = '_',
  237. resolve_likely_subtags: bool = True,
  238. ) -> Locale:
  239. """Create a `Locale` instance for the given locale identifier.
  240. >>> l = Locale.parse('de-DE', sep='-')
  241. >>> l.display_name
  242. 'Deutsch (Deutschland)'
  243. If the `identifier` parameter is not a string, but actually a `Locale`
  244. object, that object is returned:
  245. >>> Locale.parse(l)
  246. Locale('de', territory='DE')
  247. If the `identifier` parameter is neither of these, such as `None`
  248. or an empty string, e.g. because a default locale identifier
  249. could not be determined, a `TypeError` is raised:
  250. >>> Locale.parse(None)
  251. Traceback (most recent call last):
  252. ...
  253. TypeError: ...
  254. This also can perform resolving of likely subtags which it does
  255. by default. This is for instance useful to figure out the most
  256. likely locale for a territory you can use ``'und'`` as the
  257. language tag:
  258. >>> Locale.parse('und_AT')
  259. Locale('de', territory='AT')
  260. Modifiers are optional, and always at the end, separated by "@":
  261. >>> Locale.parse('de_AT@euro')
  262. Locale('de', territory='AT', modifier='euro')
  263. :param identifier: the locale identifier string
  264. :param sep: optional component separator
  265. :param resolve_likely_subtags: if this is specified then a locale will
  266. have its likely subtag resolved if the
  267. locale otherwise does not exist. For
  268. instance ``zh_TW`` by itself is not a
  269. locale that exists but Babel can
  270. automatically expand it to the full
  271. form of ``zh_hant_TW``. Note that this
  272. expansion is only taking place if no
  273. locale exists otherwise. For instance
  274. there is a locale ``en`` that can exist
  275. by itself.
  276. :raise `ValueError`: if the string does not appear to be a valid locale
  277. identifier
  278. :raise `UnknownLocaleError`: if no locale data is available for the
  279. requested locale
  280. :raise `TypeError`: if the identifier is not a string or a `Locale`
  281. :raise `ValueError`: if the identifier is not a valid string
  282. """
  283. if isinstance(identifier, Locale):
  284. return identifier
  285. if not identifier:
  286. msg = (
  287. f"Empty locale identifier value: {identifier!r}\n\n"
  288. f"If you didn't explicitly pass an empty value to a Babel function, "
  289. f"this could be caused by there being no suitable locale environment "
  290. f"variables for the API you tried to use."
  291. )
  292. if isinstance(identifier, str):
  293. # `parse_locale` would raise a ValueError, so let's do that here
  294. raise ValueError(msg)
  295. raise TypeError(msg)
  296. if not isinstance(identifier, str):
  297. raise TypeError(f"Unexpected value for identifier: {identifier!r}")
  298. parts = parse_locale(identifier, sep=sep)
  299. input_id = get_locale_identifier(parts)
  300. def _try_load(parts):
  301. try:
  302. return cls(*parts)
  303. except UnknownLocaleError:
  304. return None
  305. def _try_load_reducing(parts):
  306. # Success on first hit, return it.
  307. locale = _try_load(parts)
  308. if locale is not None:
  309. return locale
  310. # Now try without script and variant
  311. locale = _try_load(parts[:2])
  312. if locale is not None:
  313. return locale
  314. locale = _try_load(parts)
  315. if locale is not None:
  316. return locale
  317. if not resolve_likely_subtags:
  318. raise UnknownLocaleError(input_id)
  319. # From here onwards is some very bad likely subtag resolving. This
  320. # whole logic is not entirely correct but good enough (tm) for the
  321. # time being. This has been added so that zh_TW does not cause
  322. # errors for people when they upgrade. Later we should properly
  323. # implement ICU like fuzzy locale objects and provide a way to
  324. # maximize and minimize locale tags.
  325. if len(parts) == 5:
  326. language, territory, script, variant, modifier = parts
  327. else:
  328. language, territory, script, variant = parts
  329. modifier = None
  330. language = get_global('language_aliases').get(language, language)
  331. territory = get_global('territory_aliases').get(territory or '', (territory,))[0]
  332. script = get_global('script_aliases').get(script or '', script)
  333. variant = get_global('variant_aliases').get(variant or '', variant)
  334. if territory == 'ZZ':
  335. territory = None
  336. if script == 'Zzzz':
  337. script = None
  338. parts = language, territory, script, variant, modifier
  339. # First match: try the whole identifier
  340. new_id = get_locale_identifier(parts)
  341. likely_subtag = get_global('likely_subtags').get(new_id)
  342. if likely_subtag is not None:
  343. locale = _try_load_reducing(parse_locale(likely_subtag))
  344. if locale is not None:
  345. return locale
  346. # If we did not find anything so far, try again with a
  347. # simplified identifier that is just the language
  348. likely_subtag = get_global('likely_subtags').get(language)
  349. if likely_subtag is not None:
  350. parts2 = parse_locale(likely_subtag)
  351. if len(parts2) == 5:
  352. language2, _, script2, variant2, modifier2 = parts2
  353. else:
  354. language2, _, script2, variant2 = parts2
  355. modifier2 = None
  356. locale = _try_load_reducing(
  357. (language2, territory, script2, variant2, modifier2),
  358. )
  359. if locale is not None:
  360. return locale
  361. raise UnknownLocaleError(input_id)
  362. def __eq__(self, other: object) -> bool:
  363. for key in ('language', 'territory', 'script', 'variant', 'modifier'):
  364. if not hasattr(other, key):
  365. return False
  366. return (
  367. self.language == getattr(other, 'language') # noqa: B009
  368. and self.territory == getattr(other, 'territory') # noqa: B009
  369. and self.script == getattr(other, 'script') # noqa: B009
  370. and self.variant == getattr(other, 'variant') # noqa: B009
  371. and self.modifier == getattr(other, 'modifier') # noqa: B009
  372. )
  373. def __ne__(self, other: object) -> bool:
  374. return not self.__eq__(other)
  375. def __hash__(self) -> int:
  376. return hash((self.language, self.territory, self.script, self.variant, self.modifier))
  377. def __repr__(self) -> str:
  378. parameters = ['']
  379. for key in ('territory', 'script', 'variant', 'modifier'):
  380. value = getattr(self, key)
  381. if value is not None:
  382. parameters.append(f"{key}={value!r}")
  383. return f"Locale({self.language!r}{', '.join(parameters)})"
  384. def __str__(self) -> str:
  385. return get_locale_identifier(
  386. (self.language, self.territory, self.script, self.variant, self.modifier),
  387. )
  388. @property
  389. def _data(self) -> localedata.LocaleDataDict:
  390. if self.__data is None:
  391. self.__data = localedata.LocaleDataDict(localedata.load(self.__data_identifier))
  392. return self.__data
  393. def get_display_name(self, locale: Locale | str | None = None) -> str | None:
  394. """Return the display name of the locale using the given locale.
  395. The display name will include the language, territory, script, and
  396. variant, if those are specified.
  397. >>> Locale('zh', 'CN', script='Hans').get_display_name('en')
  398. 'Chinese (Simplified, China)'
  399. Modifiers are currently passed through verbatim:
  400. >>> Locale('it', 'IT', modifier='euro').get_display_name('en')
  401. 'Italian (Italy, euro)'
  402. :param locale: the locale to use
  403. """
  404. if locale is None:
  405. locale = self
  406. locale = Locale.parse(locale)
  407. retval = locale.languages.get(self.language)
  408. if retval and (self.territory or self.script or self.variant):
  409. details = []
  410. if self.script:
  411. details.append(locale.scripts.get(self.script))
  412. if self.territory:
  413. details.append(locale.territories.get(self.territory))
  414. if self.variant:
  415. details.append(locale.variants.get(self.variant))
  416. if self.modifier:
  417. details.append(self.modifier)
  418. detail_string = ', '.join(atom for atom in details if atom)
  419. if detail_string:
  420. retval += f" ({detail_string})"
  421. return retval
  422. display_name = property(
  423. get_display_name,
  424. doc="""\
  425. The localized display name of the locale.
  426. >>> Locale('en').display_name
  427. 'English'
  428. >>> Locale('en', 'US').display_name
  429. 'English (United States)'
  430. >>> Locale('sv').display_name
  431. 'svenska'
  432. :type: `unicode`
  433. """,
  434. )
  435. def get_language_name(self, locale: Locale | str | None = None) -> str | None:
  436. """Return the language of this locale in the given locale.
  437. >>> Locale('zh', 'CN', script='Hans').get_language_name('de')
  438. 'Chinesisch'
  439. .. versionadded:: 1.0
  440. :param locale: the locale to use
  441. """
  442. if locale is None:
  443. locale = self
  444. locale = Locale.parse(locale)
  445. return locale.languages.get(self.language)
  446. language_name = property(
  447. get_language_name,
  448. doc="""\
  449. The localized language name of the locale.
  450. >>> Locale('en', 'US').language_name
  451. 'English'
  452. """,
  453. )
  454. def get_territory_name(self, locale: Locale | str | None = None) -> str | None:
  455. """Return the territory name in the given locale."""
  456. if locale is None:
  457. locale = self
  458. locale = Locale.parse(locale)
  459. return locale.territories.get(self.territory or '')
  460. territory_name = property(
  461. get_territory_name,
  462. doc="""\
  463. The localized territory name of the locale if available.
  464. >>> Locale('de', 'DE').territory_name
  465. 'Deutschland'
  466. """,
  467. )
  468. def get_script_name(self, locale: Locale | str | None = None) -> str | None:
  469. """Return the script name in the given locale."""
  470. if locale is None:
  471. locale = self
  472. locale = Locale.parse(locale)
  473. return locale.scripts.get(self.script or '')
  474. script_name = property(
  475. get_script_name,
  476. doc="""\
  477. The localized script name of the locale if available.
  478. >>> Locale('sr', 'ME', script='Latn').script_name
  479. 'latinica'
  480. """,
  481. )
  482. @property
  483. def english_name(self) -> str | None:
  484. """The english display name of the locale.
  485. >>> Locale('de').english_name
  486. 'German'
  487. >>> Locale('de', 'DE').english_name
  488. 'German (Germany)'
  489. :type: `unicode`"""
  490. return self.get_display_name(Locale('en'))
  491. # { General Locale Display Names
  492. @property
  493. def languages(self) -> localedata.LocaleDataDict:
  494. """Mapping of language codes to translated language names.
  495. >>> Locale('de', 'DE').languages['ja']
  496. 'Japanisch'
  497. See `ISO 639 <https://www.loc.gov/standards/iso639-2/>`_ for
  498. more information.
  499. """
  500. return self._data['languages']
  501. @property
  502. def scripts(self) -> localedata.LocaleDataDict:
  503. """Mapping of script codes to translated script names.
  504. >>> Locale('en', 'US').scripts['Hira']
  505. 'Hiragana'
  506. See `ISO 15924 <https://www.unicode.org/iso15924/>`_
  507. for more information.
  508. """
  509. return self._data['scripts']
  510. @property
  511. def territories(self) -> localedata.LocaleDataDict:
  512. """Mapping of script codes to translated script names.
  513. >>> Locale('es', 'CO').territories['DE']
  514. 'Alemania'
  515. See `ISO 3166 <https://en.wikipedia.org/wiki/ISO_3166>`_
  516. for more information.
  517. """
  518. return self._data['territories']
  519. @property
  520. def variants(self) -> localedata.LocaleDataDict:
  521. """Mapping of script codes to translated script names.
  522. >>> Locale('de', 'DE').variants['1901']
  523. 'Alte deutsche Rechtschreibung'
  524. """
  525. return self._data['variants']
  526. # { Number Formatting
  527. @property
  528. def currencies(self) -> localedata.LocaleDataDict:
  529. """Mapping of currency codes to translated currency names. This
  530. only returns the generic form of the currency name, not the count
  531. specific one. If an actual number is requested use the
  532. :func:`babel.numbers.get_currency_name` function.
  533. >>> Locale('en').currencies['COP']
  534. 'Colombian Peso'
  535. >>> Locale('de', 'DE').currencies['COP']
  536. 'Kolumbianischer Peso'
  537. """
  538. return self._data['currency_names']
  539. @property
  540. def currency_symbols(self) -> localedata.LocaleDataDict:
  541. """Mapping of currency codes to symbols.
  542. >>> Locale('en', 'US').currency_symbols['USD']
  543. '$'
  544. >>> Locale('es', 'CO').currency_symbols['USD']
  545. 'US$'
  546. """
  547. return self._data['currency_symbols']
  548. @property
  549. def number_symbols(self) -> localedata.LocaleDataDict:
  550. """Symbols used in number formatting by number system.
  551. .. note:: The format of the value returned may change between
  552. Babel versions.
  553. >>> Locale('fr', 'FR').number_symbols["latn"]['decimal']
  554. ','
  555. >>> Locale('fa', 'IR').number_symbols["arabext"]['decimal']
  556. '٫'
  557. >>> Locale('fa', 'IR').number_symbols["latn"]['decimal']
  558. '.'
  559. """
  560. return self._data['number_symbols']
  561. @property
  562. def other_numbering_systems(self) -> localedata.LocaleDataDict:
  563. """
  564. Mapping of other numbering systems available for the locale.
  565. See: https://www.unicode.org/reports/tr35/tr35-numbers.html#otherNumberingSystems
  566. >>> Locale('el', 'GR').other_numbering_systems['traditional']
  567. 'grek'
  568. .. note:: The format of the value returned may change between
  569. Babel versions.
  570. """
  571. return self._data['numbering_systems']
  572. @property
  573. def default_numbering_system(self) -> str:
  574. """The default numbering system used by the locale.
  575. >>> Locale('el', 'GR').default_numbering_system
  576. 'latn'
  577. """
  578. return self._data['default_numbering_system']
  579. @property
  580. def decimal_formats(self) -> localedata.LocaleDataDict:
  581. """Locale patterns for decimal number formatting.
  582. .. note:: The format of the value returned may change between
  583. Babel versions.
  584. >>> Locale('en', 'US').decimal_formats[None]
  585. <NumberPattern '#,##0.###'>
  586. """
  587. return self._data['decimal_formats']
  588. @property
  589. def compact_decimal_formats(self) -> localedata.LocaleDataDict:
  590. """Locale patterns for compact decimal number formatting.
  591. .. note:: The format of the value returned may change between
  592. Babel versions.
  593. >>> Locale('en', 'US').compact_decimal_formats["short"]["one"]["1000"]
  594. <NumberPattern '0K'>
  595. """
  596. return self._data['compact_decimal_formats']
  597. @property
  598. def currency_formats(self) -> localedata.LocaleDataDict:
  599. """Locale patterns for currency number formatting.
  600. .. note:: The format of the value returned may change between
  601. Babel versions.
  602. >>> Locale('en', 'US').currency_formats['standard']
  603. <NumberPattern '\\xa4#,##0.00'>
  604. >>> Locale('en', 'US').currency_formats['accounting']
  605. <NumberPattern '\\xa4#,##0.00;(\\xa4#,##0.00)'>
  606. """
  607. return self._data['currency_formats']
  608. @property
  609. def compact_currency_formats(self) -> localedata.LocaleDataDict:
  610. """Locale patterns for compact currency number formatting.
  611. .. note:: The format of the value returned may change between
  612. Babel versions.
  613. >>> Locale('en', 'US').compact_currency_formats["short"]["one"]["1000"]
  614. <NumberPattern '¤0K'>
  615. """
  616. return self._data['compact_currency_formats']
  617. @property
  618. def percent_formats(self) -> localedata.LocaleDataDict:
  619. """Locale patterns for percent number formatting.
  620. .. note:: The format of the value returned may change between
  621. Babel versions.
  622. >>> Locale('en', 'US').percent_formats[None]
  623. <NumberPattern '#,##0%'>
  624. """
  625. return self._data['percent_formats']
  626. @property
  627. def scientific_formats(self) -> localedata.LocaleDataDict:
  628. """Locale patterns for scientific number formatting.
  629. .. note:: The format of the value returned may change between
  630. Babel versions.
  631. >>> Locale('en', 'US').scientific_formats[None]
  632. <NumberPattern '#E0'>
  633. """
  634. return self._data['scientific_formats']
  635. # { Calendar Information and Date Formatting
  636. @property
  637. def periods(self) -> localedata.LocaleDataDict:
  638. """Locale display names for day periods (AM/PM).
  639. >>> Locale('en', 'US').periods['am']
  640. 'AM'
  641. """
  642. try:
  643. return self._data['day_periods']['stand-alone']['wide']
  644. except KeyError:
  645. return localedata.LocaleDataDict({}) # pragma: no cover
  646. @property
  647. def day_periods(self) -> localedata.LocaleDataDict:
  648. """Locale display names for various day periods (not necessarily only AM/PM).
  649. These are not meant to be used without the relevant `day_period_rules`.
  650. """
  651. return self._data['day_periods']
  652. @property
  653. def day_period_rules(self) -> localedata.LocaleDataDict:
  654. """Day period rules for the locale. Used by `get_period_id`."""
  655. return self._data.get('day_period_rules', localedata.LocaleDataDict({}))
  656. @property
  657. def days(self) -> localedata.LocaleDataDict:
  658. """Locale display names for weekdays.
  659. >>> Locale('de', 'DE').days['format']['wide'][3]
  660. 'Donnerstag'
  661. """
  662. return self._data['days']
  663. @property
  664. def months(self) -> localedata.LocaleDataDict:
  665. """Locale display names for months.
  666. >>> Locale('de', 'DE').months['format']['wide'][10]
  667. 'Oktober'
  668. """
  669. return self._data['months']
  670. @property
  671. def quarters(self) -> localedata.LocaleDataDict:
  672. """Locale display names for quarters.
  673. >>> Locale('de', 'DE').quarters['format']['wide'][1]
  674. '1. Quartal'
  675. """
  676. return self._data['quarters']
  677. @property
  678. def eras(self) -> localedata.LocaleDataDict:
  679. """Locale display names for eras.
  680. .. note:: The format of the value returned may change between
  681. Babel versions.
  682. >>> Locale('en', 'US').eras['wide'][1]
  683. 'Anno Domini'
  684. >>> Locale('en', 'US').eras['abbreviated'][0]
  685. 'BC'
  686. """
  687. return self._data['eras']
  688. @property
  689. def time_zones(self) -> localedata.LocaleDataDict:
  690. """Locale display names for time zones.
  691. .. note:: The format of the value returned may change between
  692. Babel versions.
  693. >>> Locale('en', 'US').time_zones['Europe/London']['long']['daylight']
  694. 'British Summer Time'
  695. >>> Locale('en', 'US').time_zones['America/St_Johns']['city']
  696. 'St. John’s'
  697. """
  698. return self._data['time_zones']
  699. @property
  700. def meta_zones(self) -> localedata.LocaleDataDict:
  701. """Locale display names for meta time zones.
  702. Meta time zones are basically groups of different Olson time zones that
  703. have the same GMT offset and daylight savings time.
  704. .. note:: The format of the value returned may change between
  705. Babel versions.
  706. >>> Locale('en', 'US').meta_zones['Europe_Central']['long']['daylight']
  707. 'Central European Summer Time'
  708. .. versionadded:: 0.9
  709. """
  710. return self._data['meta_zones']
  711. @property
  712. def zone_formats(self) -> localedata.LocaleDataDict:
  713. """Patterns related to the formatting of time zones.
  714. .. note:: The format of the value returned may change between
  715. Babel versions.
  716. >>> Locale('en', 'US').zone_formats['fallback']
  717. '%(1)s (%(0)s)'
  718. >>> Locale('pt', 'BR').zone_formats['region']
  719. 'Horário %s'
  720. .. versionadded:: 0.9
  721. """
  722. return self._data['zone_formats']
  723. @property
  724. def first_week_day(self) -> int:
  725. """The first day of a week, with 0 being Monday.
  726. >>> Locale('de', 'DE').first_week_day
  727. 0
  728. >>> Locale('en', 'US').first_week_day
  729. 6
  730. """
  731. return self._data['week_data']['first_day']
  732. @property
  733. def weekend_start(self) -> int:
  734. """The day the weekend starts, with 0 being Monday.
  735. >>> Locale('de', 'DE').weekend_start
  736. 5
  737. """
  738. return self._data['week_data']['weekend_start']
  739. @property
  740. def weekend_end(self) -> int:
  741. """The day the weekend ends, with 0 being Monday.
  742. >>> Locale('de', 'DE').weekend_end
  743. 6
  744. """
  745. return self._data['week_data']['weekend_end']
  746. @property
  747. def min_week_days(self) -> int:
  748. """The minimum number of days in a week so that the week is counted as
  749. the first week of a year or month.
  750. >>> Locale('de', 'DE').min_week_days
  751. 4
  752. """
  753. return self._data['week_data']['min_days']
  754. @property
  755. def date_formats(self) -> localedata.LocaleDataDict:
  756. """Locale patterns for date formatting.
  757. .. note:: The format of the value returned may change between
  758. Babel versions.
  759. >>> Locale('en', 'US').date_formats['short']
  760. <DateTimePattern 'M/d/yy'>
  761. >>> Locale('fr', 'FR').date_formats['long']
  762. <DateTimePattern 'd MMMM y'>
  763. """
  764. return self._data['date_formats']
  765. @property
  766. def time_formats(self) -> localedata.LocaleDataDict:
  767. """Locale patterns for time formatting.
  768. .. note:: The format of the value returned may change between
  769. Babel versions.
  770. >>> Locale('en', 'US').time_formats['short']
  771. <DateTimePattern 'h:mm\\u202fa'>
  772. >>> Locale('fr', 'FR').time_formats['long']
  773. <DateTimePattern 'HH:mm:ss z'>
  774. """
  775. return self._data['time_formats']
  776. @property
  777. def datetime_formats(self) -> localedata.LocaleDataDict:
  778. """Locale patterns for datetime formatting.
  779. .. note:: The format of the value returned may change between
  780. Babel versions.
  781. >>> Locale('en').datetime_formats['full']
  782. '{1}, {0}'
  783. >>> Locale('th').datetime_formats['medium']
  784. '{1} {0}'
  785. """
  786. return self._data['datetime_formats']
  787. @property
  788. def datetime_skeletons(self) -> localedata.LocaleDataDict:
  789. """Locale patterns for formatting parts of a datetime.
  790. >>> Locale('en').datetime_skeletons['MEd']
  791. <DateTimePattern 'E, M/d'>
  792. >>> Locale('fr').datetime_skeletons['MEd']
  793. <DateTimePattern 'E dd/MM'>
  794. >>> Locale('fr').datetime_skeletons['H']
  795. <DateTimePattern "HH 'h'">
  796. """
  797. return self._data['datetime_skeletons']
  798. @property
  799. def interval_formats(self) -> localedata.LocaleDataDict:
  800. """Locale patterns for interval formatting.
  801. .. note:: The format of the value returned may change between
  802. Babel versions.
  803. How to format date intervals in Finnish when the day is the
  804. smallest changing component:
  805. >>> Locale('fi_FI').interval_formats['MEd']['d']
  806. ['E d.\\u2009–\\u2009', 'E d.M.']
  807. .. seealso::
  808. The primary API to use this data is :py:func:`babel.dates.format_interval`.
  809. :rtype: dict[str, dict[str, list[str]]]
  810. """
  811. return self._data['interval_formats']
  812. @property
  813. def plural_form(self) -> PluralRule:
  814. """Plural rules for the locale.
  815. >>> Locale('en').plural_form(1)
  816. 'one'
  817. >>> Locale('en').plural_form(0)
  818. 'other'
  819. >>> Locale('fr').plural_form(0)
  820. 'one'
  821. >>> Locale('ru').plural_form(100)
  822. 'many'
  823. """
  824. return self._data.get('plural_form', _default_plural_rule)
  825. @property
  826. def list_patterns(self) -> localedata.LocaleDataDict:
  827. """Patterns for generating lists
  828. .. note:: The format of the value returned may change between
  829. Babel versions.
  830. >>> Locale('en').list_patterns['standard']['start']
  831. '{0}, {1}'
  832. >>> Locale('en').list_patterns['standard']['end']
  833. '{0}, and {1}'
  834. >>> Locale('en_GB').list_patterns['standard']['end']
  835. '{0} and {1}'
  836. """
  837. return self._data['list_patterns']
  838. @property
  839. def ordinal_form(self) -> PluralRule:
  840. """Plural rules for the locale.
  841. >>> Locale('en').ordinal_form(1)
  842. 'one'
  843. >>> Locale('en').ordinal_form(2)
  844. 'two'
  845. >>> Locale('en').ordinal_form(3)
  846. 'few'
  847. >>> Locale('fr').ordinal_form(2)
  848. 'other'
  849. >>> Locale('ru').ordinal_form(100)
  850. 'other'
  851. """
  852. return self._data.get('ordinal_form', _default_plural_rule)
  853. @property
  854. def measurement_systems(self) -> localedata.LocaleDataDict:
  855. """Localized names for various measurement systems.
  856. >>> Locale('fr', 'FR').measurement_systems['US']
  857. 'américain'
  858. >>> Locale('en', 'US').measurement_systems['US']
  859. 'US'
  860. """
  861. return self._data['measurement_systems']
  862. @property
  863. def character_order(self) -> str:
  864. """The text direction for the language.
  865. >>> Locale('de', 'DE').character_order
  866. 'left-to-right'
  867. >>> Locale('ar', 'SA').character_order
  868. 'right-to-left'
  869. """
  870. return self._data['character_order']
  871. @property
  872. def text_direction(self) -> str:
  873. """The text direction for the language in CSS short-hand form.
  874. >>> Locale('de', 'DE').text_direction
  875. 'ltr'
  876. >>> Locale('ar', 'SA').text_direction
  877. 'rtl'
  878. """
  879. return ''.join(word[0] for word in self.character_order.split('-'))
  880. @property
  881. def unit_display_names(self) -> localedata.LocaleDataDict:
  882. """Display names for units of measurement.
  883. .. seealso::
  884. You may want to use :py:func:`babel.units.get_unit_name` instead.
  885. .. note:: The format of the value returned may change between
  886. Babel versions.
  887. """
  888. return self._data['unit_display_names']
  889. def default_locale(
  890. category: str | tuple[str, ...] | list[str] | None = None,
  891. aliases: Mapping[str, str] = LOCALE_ALIASES,
  892. ) -> str | None:
  893. """Returns the system default locale for a given category, based on
  894. environment variables.
  895. >>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE']:
  896. ... os.environ[name] = ''
  897. >>> os.environ['LANG'] = 'fr_FR.UTF-8'
  898. >>> default_locale('LC_MESSAGES')
  899. 'fr_FR'
  900. The "C" or "POSIX" pseudo-locales are treated as aliases for the
  901. "en_US_POSIX" locale:
  902. >>> os.environ['LC_MESSAGES'] = 'POSIX'
  903. >>> default_locale('LC_MESSAGES')
  904. 'en_US_POSIX'
  905. The following fallbacks to the variable are always considered:
  906. - ``LANGUAGE``
  907. - ``LC_ALL``
  908. - ``LC_CTYPE``
  909. - ``LANG``
  910. :param category: one or more of the ``LC_XXX`` environment variable names
  911. :param aliases: a dictionary of aliases for locale identifiers
  912. """
  913. varnames = ('LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LANG')
  914. if category:
  915. if isinstance(category, str):
  916. varnames = (category, *varnames)
  917. elif isinstance(category, (list, tuple)):
  918. varnames = (*category, *varnames)
  919. else:
  920. raise TypeError(f"Invalid type for category: {category!r}")
  921. for name in varnames:
  922. if not name:
  923. continue
  924. locale = os.getenv(name)
  925. if locale:
  926. if name == 'LANGUAGE' and ':' in locale:
  927. # the LANGUAGE variable may contain a colon-separated list of
  928. # language codes; we just pick the language on the list
  929. locale = locale.split(':')[0]
  930. if locale.split('.')[0] in ('C', 'POSIX'):
  931. locale = 'en_US_POSIX'
  932. elif aliases and locale in aliases:
  933. locale = aliases[locale]
  934. try:
  935. return get_locale_identifier(parse_locale(locale))
  936. except ValueError:
  937. pass
  938. return None
  939. def negotiate_locale(
  940. preferred: Iterable[str],
  941. available: Iterable[str],
  942. sep: str = '_',
  943. aliases: Mapping[str, str] = LOCALE_ALIASES,
  944. ) -> str | None:
  945. """Find the best match between available and requested locale strings.
  946. >>> negotiate_locale(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
  947. 'de_DE'
  948. >>> negotiate_locale(['de_DE', 'en_US'], ['en', 'de'])
  949. 'de'
  950. Case is ignored by the algorithm, the result uses the case of the preferred
  951. locale identifier:
  952. >>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at'])
  953. 'de_DE'
  954. >>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at'])
  955. 'de_DE'
  956. By default, some web browsers unfortunately do not include the territory
  957. in the locale identifier for many locales, and some don't even allow the
  958. user to easily add the territory. So while you may prefer using qualified
  959. locale identifiers in your web-application, they would not normally match
  960. the language-only locale sent by such browsers. To workaround that, this
  961. function uses a default mapping of commonly used language-only locale
  962. identifiers to identifiers including the territory:
  963. >>> negotiate_locale(['ja', 'en_US'], ['ja_JP', 'en_US'])
  964. 'ja_JP'
  965. Some browsers even use an incorrect or outdated language code, such as "no"
  966. for Norwegian, where the correct locale identifier would actually be "nb_NO"
  967. (Bokmål) or "nn_NO" (Nynorsk). The aliases are intended to take care of
  968. such cases, too:
  969. >>> negotiate_locale(['no', 'sv'], ['nb_NO', 'sv_SE'])
  970. 'nb_NO'
  971. You can override this default mapping by passing a different `aliases`
  972. dictionary to this function, or you can bypass the behavior althogher by
  973. setting the `aliases` parameter to `None`.
  974. :param preferred: the list of locale strings preferred by the user
  975. :param available: the list of locale strings available
  976. :param sep: character that separates the different parts of the locale
  977. strings
  978. :param aliases: a dictionary of aliases for locale identifiers
  979. """
  980. available = [a.lower() for a in available if a]
  981. for locale in preferred:
  982. ll = locale.lower()
  983. if ll in available:
  984. return locale
  985. if aliases:
  986. alias = aliases.get(ll)
  987. if alias:
  988. alias = alias.replace('_', sep)
  989. if alias.lower() in available:
  990. return alias
  991. parts = locale.split(sep)
  992. if len(parts) > 1 and parts[0].lower() in available:
  993. return parts[0]
  994. return None
  995. def parse_locale(
  996. identifier: str,
  997. sep: str = '_',
  998. ) -> (
  999. tuple[str, str | None, str | None, str | None]
  1000. | tuple[str, str | None, str | None, str | None, str | None]
  1001. ):
  1002. """Parse a locale identifier into a tuple of the form ``(language,
  1003. territory, script, variant, modifier)``.
  1004. >>> parse_locale('zh_CN')
  1005. ('zh', 'CN', None, None)
  1006. >>> parse_locale('zh_Hans_CN')
  1007. ('zh', 'CN', 'Hans', None)
  1008. >>> parse_locale('ca_es_valencia')
  1009. ('ca', 'ES', None, 'VALENCIA')
  1010. >>> parse_locale('en_150')
  1011. ('en', '150', None, None)
  1012. >>> parse_locale('en_us_posix')
  1013. ('en', 'US', None, 'POSIX')
  1014. >>> parse_locale('it_IT@euro')
  1015. ('it', 'IT', None, None, 'euro')
  1016. >>> parse_locale('it_IT@custom')
  1017. ('it', 'IT', None, None, 'custom')
  1018. >>> parse_locale('it_IT@')
  1019. ('it', 'IT', None, None)
  1020. The default component separator is "_", but a different separator can be
  1021. specified using the `sep` parameter.
  1022. The optional modifier is always separated with "@" and at the end:
  1023. >>> parse_locale('zh-CN', sep='-')
  1024. ('zh', 'CN', None, None)
  1025. >>> parse_locale('zh-CN@custom', sep='-')
  1026. ('zh', 'CN', None, None, 'custom')
  1027. If the identifier cannot be parsed into a locale, a `ValueError` exception
  1028. is raised:
  1029. >>> parse_locale('not_a_LOCALE_String')
  1030. Traceback (most recent call last):
  1031. ...
  1032. ValueError: 'not_a_LOCALE_String' is not a valid locale identifier
  1033. Encoding information is removed from the identifier, while modifiers are
  1034. kept:
  1035. >>> parse_locale('en_US.UTF-8')
  1036. ('en', 'US', None, None)
  1037. >>> parse_locale('de_DE.iso885915@euro')
  1038. ('de', 'DE', None, None, 'euro')
  1039. See :rfc:`4646` for more information.
  1040. :param identifier: the locale identifier string
  1041. :param sep: character that separates the different components of the locale
  1042. identifier
  1043. :raise `ValueError`: if the string does not appear to be a valid locale
  1044. identifier
  1045. """
  1046. if not identifier:
  1047. raise ValueError("empty locale identifier")
  1048. identifier, _, modifier = identifier.partition('@')
  1049. if '.' in identifier:
  1050. # this is probably the charset/encoding, which we don't care about
  1051. identifier = identifier.split('.', 1)[0]
  1052. parts = identifier.split(sep)
  1053. lang = parts.pop(0).lower()
  1054. if not lang.isalpha():
  1055. raise ValueError(f"expected only letters, got {lang!r}")
  1056. script = territory = variant = None
  1057. if parts and len(parts[0]) == 4 and parts[0].isalpha():
  1058. script = parts.pop(0).title()
  1059. if parts:
  1060. if len(parts[0]) == 2 and parts[0].isalpha():
  1061. territory = parts.pop(0).upper()
  1062. elif len(parts[0]) == 3 and parts[0].isdigit():
  1063. territory = parts.pop(0)
  1064. if parts and (
  1065. len(parts[0]) == 4
  1066. and parts[0][0].isdigit()
  1067. or len(parts[0]) >= 5
  1068. and parts[0][0].isalpha()
  1069. ):
  1070. variant = parts.pop().upper()
  1071. if parts:
  1072. raise ValueError(f"{identifier!r} is not a valid locale identifier")
  1073. # TODO(3.0): always return a 5-tuple
  1074. if modifier:
  1075. return lang, territory, script, variant, modifier
  1076. else:
  1077. return lang, territory, script, variant
  1078. def get_locale_identifier(
  1079. tup: tuple[str]
  1080. | tuple[str, str | None]
  1081. | tuple[str, str | None, str | None]
  1082. | tuple[str, str | None, str | None, str | None]
  1083. | tuple[str, str | None, str | None, str | None, str | None],
  1084. sep: str = "_",
  1085. ) -> str:
  1086. """The reverse of :func:`parse_locale`. It creates a locale identifier out
  1087. of a ``(language, territory, script, variant, modifier)`` tuple. Items can be set to
  1088. ``None`` and trailing ``None``\\s can also be left out of the tuple.
  1089. >>> get_locale_identifier(('de', 'DE', None, '1999', 'custom'))
  1090. 'de_DE_1999@custom'
  1091. >>> get_locale_identifier(('fi', None, None, None, 'custom'))
  1092. 'fi@custom'
  1093. .. versionadded:: 1.0
  1094. :param tup: the tuple as returned by :func:`parse_locale`.
  1095. :param sep: the separator for the identifier.
  1096. """
  1097. tup = tuple(tup[:5]) # type: ignore # length should be no more than 5
  1098. lang, territory, script, variant, modifier = tup + (None,) * (5 - len(tup))
  1099. ret = sep.join(filter(None, (lang, script, territory, variant)))
  1100. return f'{ret}@{modifier}' if modifier else ret
  1101. def get_cldr_version() -> str:
  1102. """Return the Unicode CLDR version used by this Babel installation.
  1103. Generally, you should be able to assume that the return value of this
  1104. function is a string representing a version number, e.g. '47'.
  1105. >>> get_cldr_version()
  1106. '47'
  1107. .. versionadded:: 2.18
  1108. :rtype: str
  1109. """
  1110. return str(get_global("cldr")["version"])