Skip to content

Commit 1174cd1

Browse files
authored
Merge pull request #1164 from python-babel/locale-none
Improve handling for `locale=None`
2 parents 6bbdc0e + 9327e5f commit 1174cd1

File tree

12 files changed

+257
-159
lines changed

12 files changed

+257
-159
lines changed

babel/core.py

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ def negotiate(
269269
@classmethod
270270
def parse(
271271
cls,
272-
identifier: str | Locale | None,
272+
identifier: Locale | str | None,
273273
sep: str = '_',
274274
resolve_likely_subtags: bool = True,
275275
) -> Locale:
@@ -286,8 +286,8 @@ def parse(
286286
Locale('de', territory='DE')
287287
288288
If the `identifier` parameter is neither of these, such as `None`
289-
e.g. because a default locale identifier could not be determined,
290-
a `TypeError` is raised:
289+
or an empty string, e.g. because a default locale identifier
290+
could not be determined, a `TypeError` is raised:
291291
292292
>>> Locale.parse(None)
293293
Traceback (most recent call last):
@@ -325,10 +325,23 @@ def parse(
325325
:raise `UnknownLocaleError`: if no locale data is available for the
326326
requested locale
327327
:raise `TypeError`: if the identifier is not a string or a `Locale`
328+
:raise `ValueError`: if the identifier is not a valid string
328329
"""
329330
if isinstance(identifier, Locale):
330331
return identifier
331-
elif not isinstance(identifier, str):
332+
333+
if not identifier:
334+
msg = (
335+
f"Empty locale identifier value: {identifier!r}\n\n"
336+
f"If you didn't explicitly pass an empty value to a Babel function, "
337+
f"this could be caused by there being no suitable locale environment "
338+
f"variables for the API you tried to use.",
339+
)
340+
if isinstance(identifier, str):
341+
raise ValueError(msg) # `parse_locale` would raise a ValueError, so let's do that here
342+
raise TypeError(msg)
343+
344+
if not isinstance(identifier, str):
332345
raise TypeError(f"Unexpected value for identifier: {identifier!r}")
333346

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

0 commit comments

Comments
 (0)