Skip to content

Commit

Permalink
Improve type annotation for babel.support.Translations.load
Browse files Browse the repository at this point in the history
Fixes #982
  • Loading branch information
akx committed Mar 2, 2023
1 parent 94e533f commit 9487b2e
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions babel/support.py
Original file line number Diff line number Diff line change
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,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]

0 comments on commit 9487b2e

Please sign in to comment.