codekingpro/portable-devtools
114k
1from __future__ import annotations2 3from babel.core import get_global4 5 6def get_official_languages(territory: str, regional: bool = False, de_facto: bool = False) -> tuple[str, ...]:7 """8 Get the official language(s) for the given territory.9 10 The language codes, if any are known, are returned in order of descending popularity.11 12 If the `regional` flag is set, then languages which are regionally official are also returned.13 14 If the `de_facto` flag is set, then languages which are "de facto" official are also returned.15 16 .. warning:: Note that the data is as up to date as the current version of the CLDR used17 by Babel. If you need scientifically accurate information, use another source!18 19 :param territory: Territory code20 :type territory: str21 :param regional: Whether to return regionally official languages too22 :type regional: bool23 :param de_facto: Whether to return de-facto official languages too24 :type de_facto: bool25 :return: Tuple of language codes26 :rtype: tuple[str]27 """28 29 territory = str(territory).upper()30 allowed_stati = {"official"}31 if regional:32 allowed_stati.add("official_regional")33 if de_facto:34 allowed_stati.add("de_facto_official")35 36 languages = get_global("territory_languages").get(territory, {})37 pairs = [38 (info['population_percent'], language)39 for language, info in languages.items()40 if info.get('official_status') in allowed_stati41 ]42 pairs.sort(reverse=True)43 return tuple(lang for _, lang in pairs)44 45 46def get_territory_language_info(territory: str) -> dict[str, dict[str, float | str | None]]:47 """48 Get a dictionary of language information for a territory.49 50 The dictionary is keyed by language code; the values are dicts with more information.51 52 The following keys are currently known for the values:53 54 * `population_percent`: The percentage of the territory's population speaking the55 language.56 * `official_status`: An optional string describing the officiality status of the language.57 Known values are "official", "official_regional" and "de_facto_official".58 59 .. warning:: Note that the data is as up to date as the current version of the CLDR used60 by Babel. If you need scientifically accurate information, use another source!61 62 .. note:: Note that the format of the dict returned may change between Babel versions.63 64 See https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html65 66 :param territory: Territory code67 :type territory: str68 :return: Language information dictionary69 :rtype: dict[str, dict]70 """71 territory = str(territory).upper()72 return get_global("territory_languages").get(territory, {}).copy()73 