Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve type annotation for babel.support.Translations.load #983

Merged
merged 2 commits into from Mar 2, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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]