From 9487b2ead7f3594096737a386796bb11d80d220f Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Thu, 2 Mar 2023 15:55:45 +0200 Subject: [PATCH 1/2] Improve type annotation for `babel.support.Translations.load` Fixes #982 --- babel/support.py | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/babel/support.py b/babel/support.py index d6ff73aa2..1b6056fea 100644 --- a/babel/support.py +++ b/babel/support.py @@ -17,7 +17,7 @@ import locale import os from collections.abc import Iterator -from typing import TYPE_CHECKING, Any, Callable +from typing import TYPE_CHECKING, Any, Callable, Iterable from babel.core import Locale from babel.dates import format_date, format_datetime, format_time, format_timedelta @@ -615,7 +615,7 @@ def __init__(self, fp: gettext._TranslationsReader | None = None, domain: str | def load( cls, dirname: str | os.PathLike[str] | None = None, - locales: list[str] | tuple[str, ...] | str | None = None, + locales: Iterable[str | Locale] | str | Locale | None = None, domain: str | None = None, ) -> NullTranslations: """Load translations from the given directory. @@ -626,13 +626,9 @@ def load( strings) :param domain: the message domain (default: 'messages') """ - if locales is not None: - if not isinstance(locales, (list, tuple)): - locales = [locales] - locales = [str(locale) for locale in locales] if not domain: domain = cls.DEFAULT_DOMAIN - filename = gettext.find(domain, dirname, locales) + filename = gettext.find(domain, dirname, _locales_to_names(locales)) if not filename: return NullTranslations() with open(filename, 'rb') as fp: @@ -683,3 +679,18 @@ def merge(self, translations: Translations): self.files.extend(translations.files) return self + + +def _locales_to_names( + locales: Iterable[str | Locale] | str | Locale | None, +) -> list[str] | None: + """ + Normalize a `locales` argument to a list of locale names. + """ + if locales is None: + return None + if isinstance(locales, Locale): + return [str(locale)] + if isinstance(locales, str): + return [locales] + return [str(locale) for locale in locales] From 8553928447328886c39fa928b69e69d7e8808491 Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Thu, 2 Mar 2023 16:08:27 +0200 Subject: [PATCH 2/2] Update babel/support.py Co-authored-by: Jonah Lawrence --- babel/support.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/babel/support.py b/babel/support.py index 1b6056fea..40ce9814d 100644 --- a/babel/support.py +++ b/babel/support.py @@ -684,8 +684,11 @@ def merge(self, translations: Translations): def _locales_to_names( locales: Iterable[str | Locale] | str | Locale | None, ) -> list[str] | None: - """ - Normalize a `locales` argument to a list of locale names. + """Normalize a `locales` argument to a list of locale names. + + :param locales: the list of locales in order of preference (items in + this list can be either `Locale` objects or locale + strings) """ if locales is None: return None