Skip to content

Commit 47ef03b

Browse files
committed
Revert "Numbers and core type fixes"
1 parent fef8fc4 commit 47ef03b

File tree

2 files changed

+42
-33
lines changed

2 files changed

+42
-33
lines changed

babel/core.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import os
1414
import pickle
1515
from collections.abc import Iterable, Mapping
16-
from typing import TYPE_CHECKING, Any
16+
from typing import TYPE_CHECKING, Any, overload
1717

1818
from babel import localedata
1919
from babel.plural import PluralRule
@@ -262,13 +262,21 @@ def negotiate(
262262
if identifier:
263263
return Locale.parse(identifier, sep=sep)
264264

265+
@overload
266+
@classmethod
267+
def parse(cls, identifier: None, sep: str = ..., resolve_likely_subtags: bool = ...) -> None: ...
268+
269+
@overload
270+
@classmethod
271+
def parse(cls, identifier: str | Locale, sep: str = ..., resolve_likely_subtags: bool = ...) -> Locale: ...
272+
265273
@classmethod
266274
def parse(
267275
cls,
268276
identifier: str | Locale | None,
269277
sep: str = '_',
270278
resolve_likely_subtags: bool = True,
271-
) -> Locale:
279+
) -> Locale | None:
272280
"""Create a `Locale` instance for the given locale identifier.
273281
274282
>>> l = Locale.parse('de-DE', sep='-')
@@ -308,12 +316,14 @@ def parse(
308316
there is a locale ``en`` that can exist
309317
by itself.
310318
:raise `ValueError`: if the string does not appear to be a valid locale
311-
identifier or ``None`` is passed
319+
identifier
312320
:raise `UnknownLocaleError`: if no locale data is available for the
313321
requested locale
314322
:raise `TypeError`: if the identifier is not a string or a `Locale`
315323
"""
316-
if isinstance(identifier, Locale):
324+
if identifier is None:
325+
return None
326+
elif isinstance(identifier, Locale):
317327
return identifier
318328
elif not isinstance(identifier, str):
319329
raise TypeError(f"Unexpected value for identifier: {identifier!r}")
@@ -357,9 +367,9 @@ def _try_load_reducing(parts):
357367
language, territory, script, variant = parts
358368
modifier = None
359369
language = get_global('language_aliases').get(language, language)
360-
territory = get_global('territory_aliases').get(territory or '', (territory,))[0]
361-
script = get_global('script_aliases').get(script or '', script)
362-
variant = get_global('variant_aliases').get(variant or '', variant)
370+
territory = get_global('territory_aliases').get(territory, (territory,))[0]
371+
script = get_global('script_aliases').get(script, script)
372+
variant = get_global('variant_aliases').get(variant, variant)
363373

364374
if territory == 'ZZ':
365375
territory = None
@@ -382,9 +392,9 @@ def _try_load_reducing(parts):
382392
if likely_subtag is not None:
383393
parts2 = parse_locale(likely_subtag)
384394
if len(parts2) == 5:
385-
language2, _, script2, variant2, modifier2 = parts2
395+
language2, _, script2, variant2, modifier2 = parse_locale(likely_subtag)
386396
else:
387-
language2, _, script2, variant2 = parts2
397+
language2, _, script2, variant2 = parse_locale(likely_subtag)
388398
modifier2 = None
389399
locale = _try_load_reducing((language2, territory, script2, variant2, modifier2))
390400
if locale is not None:
@@ -1178,7 +1188,7 @@ def negotiate_locale(preferred: Iterable[str], available: Iterable[str], sep: st
11781188
def parse_locale(
11791189
identifier: str,
11801190
sep: str = '_'
1181-
) -> tuple[str, str | None, str | None, str | None] | tuple[str, str | None, str | None, str | None, str | None]:
1191+
) -> tuple[str, str | None, str | None, str | None, str | None]:
11821192
"""Parse a locale identifier into a tuple of the form ``(language,
11831193
territory, script, variant, modifier)``.
11841194

babel/numbers.py

Lines changed: 22 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
import decimal
2424
import re
2525
import warnings
26-
from typing import TYPE_CHECKING, Any, cast, overload
26+
from typing import TYPE_CHECKING, Any, overload
2727

2828
from babel.core import Locale, default_locale, get_global
2929
from babel.localedata import LocaleDataDict
@@ -428,7 +428,7 @@ def get_decimal_quantum(precision: int | decimal.Decimal) -> decimal.Decimal:
428428

429429
def format_decimal(
430430
number: float | decimal.Decimal | str,
431-
format: str | NumberPattern | None = None,
431+
format: str | None = None,
432432
locale: Locale | str | None = LC_NUMERIC,
433433
decimal_quantization: bool = True,
434434
group_separator: bool = True,
@@ -474,8 +474,8 @@ def format_decimal(
474474
number format.
475475
"""
476476
locale = Locale.parse(locale)
477-
if format is None:
478-
format = locale.decimal_formats[format]
477+
if not format:
478+
format = locale.decimal_formats.get(format)
479479
pattern = parse_pattern(format)
480480
return pattern.apply(
481481
number, locale, decimal_quantization=decimal_quantization, group_separator=group_separator)
@@ -513,15 +513,15 @@ def format_compact_decimal(
513513
number, format = _get_compact_format(number, compact_format, locale, fraction_digits)
514514
# Did not find a format, fall back.
515515
if format is None:
516-
format = locale.decimal_formats[None]
516+
format = locale.decimal_formats.get(None)
517517
pattern = parse_pattern(format)
518518
return pattern.apply(number, locale, decimal_quantization=False)
519519

520520

521521
def _get_compact_format(
522522
number: float | decimal.Decimal | str,
523523
compact_format: LocaleDataDict,
524-
locale: Locale,
524+
locale: Locale | str | None,
525525
fraction_digits: int,
526526
) -> tuple[decimal.Decimal, NumberPattern | None]:
527527
"""Returns the number after dividing by the unit and the format pattern to use.
@@ -543,7 +543,7 @@ def _get_compact_format(
543543
break
544544
# otherwise, we need to divide the number by the magnitude but remove zeros
545545
# equal to the number of 0's in the pattern minus 1
546-
number = cast(decimal.Decimal, number / (magnitude // (10 ** (pattern.count("0") - 1))))
546+
number = number / (magnitude // (10 ** (pattern.count("0") - 1)))
547547
# round to the number of fraction digits requested
548548
rounded = round(number, fraction_digits)
549549
# if the remaining number is singular, use the singular format
@@ -565,7 +565,7 @@ class UnknownCurrencyFormatError(KeyError):
565565
def format_currency(
566566
number: float | decimal.Decimal | str,
567567
currency: str,
568-
format: str | NumberPattern | None = None,
568+
format: str | None = None,
569569
locale: Locale | str | None = LC_NUMERIC,
570570
currency_digits: bool = True,
571571
format_type: Literal["name", "standard", "accounting"] = "standard",
@@ -680,7 +680,7 @@ def format_currency(
680680
def _format_currency_long_name(
681681
number: float | decimal.Decimal | str,
682682
currency: str,
683-
format: str | NumberPattern | None = None,
683+
format: str | None = None,
684684
locale: Locale | str | None = LC_NUMERIC,
685685
currency_digits: bool = True,
686686
format_type: Literal["name", "standard", "accounting"] = "standard",
@@ -706,7 +706,7 @@ def _format_currency_long_name(
706706

707707
# Step 5.
708708
if not format:
709-
format = locale.decimal_formats[format]
709+
format = locale.decimal_formats.get(format)
710710

711711
pattern = parse_pattern(format)
712712

@@ -758,15 +758,13 @@ def format_compact_currency(
758758
# compress adjacent spaces into one
759759
format = re.sub(r'(\s)\s+', r'\1', format).strip()
760760
break
761-
if format is None:
762-
raise ValueError('No compact currency format found for the given number and locale.')
763761
pattern = parse_pattern(format)
764762
return pattern.apply(number, locale, currency=currency, currency_digits=False, decimal_quantization=False)
765763

766764

767765
def format_percent(
768766
number: float | decimal.Decimal | str,
769-
format: str | NumberPattern | None = None,
767+
format: str | None = None,
770768
locale: Locale | str | None = LC_NUMERIC,
771769
decimal_quantization: bool = True,
772770
group_separator: bool = True,
@@ -810,15 +808,15 @@ def format_percent(
810808
"""
811809
locale = Locale.parse(locale)
812810
if not format:
813-
format = locale.percent_formats[format]
811+
format = locale.percent_formats.get(format)
814812
pattern = parse_pattern(format)
815813
return pattern.apply(
816814
number, locale, decimal_quantization=decimal_quantization, group_separator=group_separator)
817815

818816

819817
def format_scientific(
820818
number: float | decimal.Decimal | str,
821-
format: str | NumberPattern | None = None,
819+
format: str | None = None,
822820
locale: Locale | str | None = LC_NUMERIC,
823821
decimal_quantization: bool = True,
824822
) -> str:
@@ -849,7 +847,7 @@ def format_scientific(
849847
"""
850848
locale = Locale.parse(locale)
851849
if not format:
852-
format = locale.scientific_formats[format]
850+
format = locale.scientific_formats.get(format)
853851
pattern = parse_pattern(format)
854852
return pattern.apply(
855853
number, locale, decimal_quantization=decimal_quantization)
@@ -858,7 +856,7 @@ def format_scientific(
858856
class NumberFormatError(ValueError):
859857
"""Exception raised when a string cannot be parsed into a number."""
860858

861-
def __init__(self, message: str, suggestions: list[str] | None = None) -> None:
859+
def __init__(self, message: str, suggestions: str | None = None) -> None:
862860
super().__init__(message)
863861
#: a list of properly formatted numbers derived from the invalid input
864862
self.suggestions = suggestions
@@ -1142,7 +1140,7 @@ def scientific_notation_elements(self, value: decimal.Decimal, locale: Locale |
11421140

11431141
def apply(
11441142
self,
1145-
value: float | decimal.Decimal | str,
1143+
value: float | decimal.Decimal,
11461144
locale: Locale | str | None,
11471145
currency: str | None = None,
11481146
currency_digits: bool = True,
@@ -1213,9 +1211,9 @@ def apply(
12131211
number = ''.join([
12141212
self._quantize_value(value, locale, frac_prec, group_separator),
12151213
get_exponential_symbol(locale),
1216-
exp_sign, # type: ignore # exp_sign is always defined here
1217-
self._format_int(str(exp), self.exp_prec[0], self.exp_prec[1], locale) # type: ignore # exp is always defined here
1218-
])
1214+
exp_sign,
1215+
self._format_int(
1216+
str(exp), self.exp_prec[0], self.exp_prec[1], locale)])
12191217

12201218
# Is it a significant digits pattern?
12211219
elif '@' in self.pattern:
@@ -1236,8 +1234,9 @@ def apply(
12361234
number if self.number_pattern != '' else '',
12371235
self.suffix[is_negative]])
12381236

1239-
if '¤' in retval and currency is not None:
1240-
retval = retval.replace('¤¤¤', get_currency_name(currency, value, locale))
1237+
if '¤' in retval:
1238+
retval = retval.replace('¤¤¤',
1239+
get_currency_name(currency, value, locale))
12411240
retval = retval.replace('¤¤', currency.upper())
12421241
retval = retval.replace('¤', get_currency_symbol(currency, locale))
12431242

0 commit comments

Comments
 (0)