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 handling for locale=None #1164

Merged
merged 5 commits into from
Jan 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions babel/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ def negotiate(
@classmethod
def parse(
cls,
identifier: str | Locale | None,
identifier: Locale | str | None,
sep: str = '_',
resolve_likely_subtags: bool = True,
) -> Locale:
Expand All @@ -286,8 +286,8 @@ def parse(
Locale('de', territory='DE')

If the `identifier` parameter is neither of these, such as `None`
e.g. because a default locale identifier could not be determined,
a `TypeError` is raised:
or an empty string, e.g. because a default locale identifier
could not be determined, a `TypeError` is raised:

>>> Locale.parse(None)
Traceback (most recent call last):
Expand Down Expand Up @@ -325,10 +325,23 @@ def parse(
:raise `UnknownLocaleError`: if no locale data is available for the
requested locale
:raise `TypeError`: if the identifier is not a string or a `Locale`
:raise `ValueError`: if the identifier is not a valid string
"""
if isinstance(identifier, Locale):
return identifier
elif not isinstance(identifier, str):

if not identifier:
msg = (
f"Empty locale identifier value: {identifier!r}\n\n"
f"If you didn't explicitly pass an empty value to a Babel function, "
f"this could be caused by there being no suitable locale environment "
f"variables for the API you tried to use.",
)
if isinstance(identifier, str):
raise ValueError(msg) # `parse_locale` would raise a ValueError, so let's do that here
raise TypeError(msg)

if not isinstance(identifier, str):
raise TypeError(f"Unexpected value for identifier: {identifier!r}")

parts = parse_locale(identifier, sep=sep)
Expand Down Expand Up @@ -1235,6 +1248,8 @@ def parse_locale(
:raise `ValueError`: if the string does not appear to be a valid locale
identifier
"""
if not identifier:
raise ValueError("empty locale identifier")
identifier, _, modifier = identifier.partition('@')
if '.' in identifier:
# this is probably the charset/encoding, which we don't care about
Expand Down
Loading
Loading