Skip to content

Commit

Permalink
Improve type annotation for babel.support.Translations.load (#983)
Browse files Browse the repository at this point in the history
Fixes #982

Co-authored-by: Jonah Lawrence <jonah@freshidea.com>
  • Loading branch information
akx and DenverCoder1 committed Mar 2, 2023
1 parent 94e533f commit 92e6fab
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions babel/support.py
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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:
Expand Down Expand Up @@ -683,3 +679,21 @@ 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.
: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
if isinstance(locales, Locale):
return [str(locale)]
if isinstance(locales, str):
return [locales]
return [str(locale) for locale in locales]

0 comments on commit 92e6fab

Please sign in to comment.