python-intl 0.8.0__py3-none-any.whl → 0.10.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
python_intl/__init__.py CHANGED
@@ -5,7 +5,12 @@ from .collator import (
5
5
  from .datetimeformat import (
6
6
  DateTimeFormat as DateTimeFormat,
7
7
  DateTimeFormatOptions as DateTimeFormatOptions,
8
- DateTimeIntervalPatternPart as DateTimeIntervalPatternPart,
9
- DateTimePatternPart as DateTimePatternPart,
10
- FormatPatternNotFoundException as FormatPatternNotFoundException,
8
+ DateTimeFormattedPart as DateTimeFormattedPart,
9
+ DateTimeIntervalFormattedPart as DateTimeIntervalFormattedPart,
10
+ FormatPatternNotFoundError as FormatPatternNotFoundError,
11
+ )
12
+ from .numberformat import (
13
+ InvalidNumberFormatOptionError as InvalidNumberFormatOptionError,
14
+ NumberFormat as NumberFormat,
15
+ NumberFormatOptions as NumberFormatOptions,
11
16
  )
python_intl/_types.py CHANGED
@@ -7,6 +7,7 @@ if TYPE_CHECKING:
7
7
  type Hour12T = bool
8
8
  type HourCycleT = Literal["h11", "h12", "h23", "h24"]
9
9
 
10
+ # datetime
10
11
  type EraFormatT = Literal["long", "short", "narrow"]
11
12
  type YearFormatT = Literal["numeric", "2-digit"]
12
13
  type MonthFormatT = Literal["numeric", "2-digit", "long", "short", "narrow"]
@@ -26,6 +27,65 @@ if TYPE_CHECKING:
26
27
  "long_generic",
27
28
  ]
28
29
 
30
+ # number
31
+ type StyleT = Literal["decimal", "currency", "percent", "unit"]
32
+ type CurrencyT = str # 3 char ISO code
33
+ type CurrencyDisplayT = Literal["code", "symbol", "narrow_symbol", "name"]
34
+ type CurrencySignT = Literal["standard", "accounting"]
35
+ type UnitT = Literal[
36
+ # see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/supportedValuesOf#supported_unit_identifiers
37
+ # for Intl reference
38
+ # see https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classicu_1_1MeasureUnit.html
39
+ # for ICU reference
40
+ "acre",
41
+ "bit",
42
+ "byte",
43
+ "celsius",
44
+ "centimeter",
45
+ "day",
46
+ "degree",
47
+ "fahrenheit",
48
+ "fluid-ounce",
49
+ "foot",
50
+ "gallon",
51
+ "gigabit",
52
+ "gigabyte",
53
+ "gram",
54
+ "hectare",
55
+ "hour",
56
+ "inch",
57
+ "kilobit",
58
+ "kilobyte",
59
+ "kilogram",
60
+ "kilometer",
61
+ "liter",
62
+ "megabit",
63
+ "megabyte",
64
+ "meter",
65
+ "microsecond",
66
+ "mile",
67
+ "mile-scandinavian",
68
+ "milliliter",
69
+ "millimeter",
70
+ "millisecond",
71
+ "minute",
72
+ "month",
73
+ "nanosecond",
74
+ "ounce",
75
+ "percent",
76
+ "petabyte",
77
+ "pound",
78
+ "second",
79
+ "stone",
80
+ "terabit",
81
+ "terabyte",
82
+ "week",
83
+ "yard",
84
+ "year",
85
+ ]
86
+ type UnitDisplayT = Literal["short", "narrow", "long"]
87
+
88
+ # collator
29
89
  # type UsageT = Literal["sort", "search"]
30
90
  # type CollationT = Literal["emoji", "pinyin", "stroke"]
31
91
  type CaseFirstT = Literal["upper", "lower", "false"]
python_intl/collator.py CHANGED
@@ -2,15 +2,15 @@ from __future__ import annotations
2
2
 
3
3
  import dataclasses
4
4
  import functools
5
- from collections.abc import Callable, Iterable
6
5
  from functools import cached_property
7
6
  from typing import TYPE_CHECKING, overload
8
7
 
9
- import icu # type: ignore[import-untyped]
8
+ import icu
10
9
 
11
10
  from .locale import Locale
12
11
 
13
12
  if TYPE_CHECKING:
13
+ from collections.abc import Callable, Iterable
14
14
  from typing import NotRequired, TypedDict
15
15
 
16
16
  from ._types import CaseFirstT, ComparisonResultT, LocaleMatcherT, SensitivityT
@@ -54,10 +54,10 @@ class CollatorOptions:
54
54
  }
55
55
 
56
56
 
57
- _COLLATOR_RESULT_TO_RESULT: dict[icu.UCollationResult, ComparisonResultT] = { # ty: ignore[unresolved-attribute]
58
- icu.UCollationResult.LESS: -1, # ty: ignore[unresolved-attribute]
59
- icu.UCollationResult.EQUAL: 0, # ty: ignore[unresolved-attribute]
60
- icu.UCollationResult.GREATER: 1, # ty: ignore[unresolved-attribute]
57
+ _COLLATOR_RESULT_TO_RESULT: dict[icu.UCollationResult, ComparisonResultT] = {
58
+ icu.UCollationResult.LESS: -1,
59
+ icu.UCollationResult.EQUAL: 0,
60
+ icu.UCollationResult.GREATER: 1,
61
61
  }
62
62
 
63
63
 
@@ -82,11 +82,11 @@ class Collator:
82
82
  self.options = CollatorOptions(**options)
83
83
 
84
84
  @cached_property
85
- def _icu_collator(self) -> icu.Collator: # ty: ignore[unresolved-attribute]
86
- collator = icu.Collator.createInstance(self.locale._icu_locale) # ty: ignore[unresolved-attribute]
85
+ def _icu_collator(self) -> icu.Collator:
86
+ collator = icu.Collator.createInstance(self.locale._icu_locale)
87
87
 
88
88
  if self.options.numeric:
89
- collator.setAttribute(icu.UCollAttribute.NUMERIC_COLLATION, icu.UCollAttributeValue.ON) # ty: ignore[unresolved-attribute]
89
+ collator.setAttribute(icu.UCollAttribute.NUMERIC_COLLATION, icu.UCollAttributeValue.ON)
90
90
 
91
91
  if (
92
92
  self.options.ignore_punctuation
@@ -95,24 +95,24 @@ class Collator:
95
95
  and self.locale._icu_locale.getLanguage() == "th"
96
96
  )
97
97
  ):
98
- collator.setAttribute(icu.UCollAttribute.ALTERNATE_HANDLING, icu.UCollAttributeValue.SHIFTED) # ty: ignore[unresolved-attribute]
98
+ collator.setAttribute(icu.UCollAttribute.ALTERNATE_HANDLING, icu.UCollAttributeValue.SHIFTED)
99
99
 
100
100
  match self.options.case_first:
101
101
  case "upper":
102
- collator.setAttribute(icu.UCollAttribute.CASE_FIRST, icu.UCollAttributeValue.UPPER_FIRST) # ty: ignore[unresolved-attribute]
102
+ collator.setAttribute(icu.UCollAttribute.CASE_FIRST, icu.UCollAttributeValue.UPPER_FIRST)
103
103
  case "lower":
104
- collator.setAttribute(icu.UCollAttribute.CASE_FIRST, icu.UCollAttributeValue.LOWER_FIRST) # ty: ignore[unresolved-attribute]
104
+ collator.setAttribute(icu.UCollAttribute.CASE_FIRST, icu.UCollAttributeValue.LOWER_FIRST)
105
105
 
106
- collator.setAttribute(icu.UCollAttribute.NORMALIZATION_MODE, icu.UCollAttributeValue.ON) # ty: ignore[unresolved-attribute]
106
+ collator.setAttribute(icu.UCollAttribute.NORMALIZATION_MODE, icu.UCollAttributeValue.ON)
107
107
  match self.options.sensitivity:
108
108
  case "base":
109
- collator.setAttribute(icu.UCollAttribute.STRENGTH, icu.UCollAttributeValue.PRIMARY) # ty: ignore[unresolved-attribute]
109
+ collator.setAttribute(icu.UCollAttribute.STRENGTH, icu.UCollAttributeValue.PRIMARY)
110
110
  case "accent":
111
- collator.setAttribute(icu.UCollAttribute.STRENGTH, icu.UCollAttributeValue.SECONDARY) # ty: ignore[unresolved-attribute]
111
+ collator.setAttribute(icu.UCollAttribute.STRENGTH, icu.UCollAttributeValue.SECONDARY)
112
112
  case "case":
113
- collator.setAttribute(icu.UCollAttribute.STRENGTH, icu.UCollAttributeValue.TERTIARY) # ty: ignore[unresolved-attribute]
113
+ collator.setAttribute(icu.UCollAttribute.STRENGTH, icu.UCollAttributeValue.TERTIARY)
114
114
  case "variant":
115
- collator.setAttribute(icu.UCollAttribute.STRENGTH, icu.UCollAttributeValue.QUATERNARY) # ty: ignore[unresolved-attribute]
115
+ collator.setAttribute(icu.UCollAttribute.STRENGTH, icu.UCollAttributeValue.QUATERNARY)
116
116
 
117
117
  return collator
118
118
 
@@ -123,7 +123,7 @@ class Collator:
123
123
  def sorted(self, items: Iterable[str], /, key: None = None) -> Iterable[str]: ...
124
124
  @overload
125
125
  def sorted[T](self, items: Iterable[T], /, key: Callable[[T], str]) -> Iterable[T]: ...
126
- def sorted(self, items, /, key = None):
126
+ def sorted(self, items, /, key = None): # pyright: ignore[reportInconsistentOverload]
127
127
  return sorted(
128
128
  items,
129
129
  key=functools.cmp_to_key(
@@ -1,15 +1,15 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import dataclasses
4
- import datetime as dt
5
- from functools import cache, cached_property
6
- from typing import TYPE_CHECKING, Literal
4
+ from functools import cached_property
5
+ from typing import TYPE_CHECKING, Literal, override
7
6
 
8
- import icu # type: ignore[import-untyped]
7
+ import icu
9
8
 
10
9
  from .locale import Locale
11
10
 
12
11
  if TYPE_CHECKING:
12
+ import datetime as dt
13
13
  from collections.abc import Iterable
14
14
  from typing import NotRequired, TypedDict
15
15
 
@@ -30,7 +30,7 @@ if TYPE_CHECKING:
30
30
  YearFormatT,
31
31
  )
32
32
 
33
- type DatetimePatternPartTypeT = Literal[
33
+ type DatetimeFormattedPartTypeT = Literal[
34
34
  "literal", "unknown",
35
35
  "era", "year", "month", "weekday", "day", "day_period",
36
36
  "hour", "minute", "second", "fraction_second_digits",
@@ -58,7 +58,7 @@ if TYPE_CHECKING:
58
58
  time_zone_name: NotRequired[TimezoneNameFormatT]
59
59
 
60
60
  _PATTERN_SYMBOLS = "GyYuUrQqMLqQdDFgEecabBhHkKmsSAzZOvVxX" # includes unused
61
- _PATTERN_SYMBOL_TO_TYPE: dict[str, DatetimePatternPartTypeT] = {
61
+ _PATTERN_SYMBOL_TO_TYPE: dict[str, DatetimeFormattedPartTypeT] = {
62
62
  "G": "era",
63
63
  "y": "year",
64
64
  "Y": "year",
@@ -89,27 +89,36 @@ _PATTERN_SYMBOL_TO_TYPE: dict[str, DatetimePatternPartTypeT] = {
89
89
  "x": "time_zone_name",
90
90
  "X": "time_zone_name",
91
91
  }
92
- _PATTERN_FIELD_TO_TYPE: dict[icu.UDateTimePatternField, DatetimePatternPartTypeT] = { # ty: ignore[unresolved-attribute]
93
- icu.DateFormat.ERA_FIELD: "era", # ty: ignore[unresolved-attribute]
94
- icu.DateFormat.YEAR_FIELD: "year", # ty: ignore[unresolved-attribute]
95
- icu.DateFormat.MONTH_FIELD: "month", # ty: ignore[unresolved-attribute]
96
- icu.DateFormat.DAY_OF_WEEK_FIELD: "weekday", # ty: ignore[unresolved-attribute]
97
- icu.DateFormat.DATE_FIELD: "day", # ty: ignore[unresolved-attribute]
98
- icu.DateFormat.AM_PM_FIELD: "day_period", # ty: ignore[unresolved-attribute]
99
- # TODO(ddanier): Use this instead once PyICU has those values in the enum:
100
- # https://gitlab.pyicu.org/main/pyicu/-/work_items/180
101
- # icu.DateFormat.AM_PM_MIDNIGHT_NOON_FIELD: "day_period",
102
- # icu.DateFormat.FLEXIBLE_DAY_PERIOD_FIELD: "day_period",
103
- 35: "day_period",
104
- 36: "day_period",
105
- icu.DateFormat.HOUR0_FIELD: "hour", # ty: ignore[unresolved-attribute]
106
- icu.DateFormat.HOUR1_FIELD: "hour", # ty: ignore[unresolved-attribute]
107
- icu.DateFormat.HOUR_OF_DAY0_FIELD: "hour", # ty: ignore[unresolved-attribute]
108
- icu.DateFormat.HOUR_OF_DAY1_FIELD: "hour", # ty: ignore[unresolved-attribute]
109
- icu.DateFormat.MINUTE_FIELD: "minute", # ty: ignore[unresolved-attribute]
110
- icu.DateFormat.SECOND_FIELD: "second", # ty: ignore[unresolved-attribute]
111
- icu.DateFormat.MILLISECOND_FIELD: "fraction_second_digits", # ty: ignore[unresolved-attribute]
112
- icu.DateFormat.TIMEZONE_FIELD: "time_zone_name", # ty: ignore[unresolved-attribute]
92
+ _PATTERN_FIELD_TO_TYPE: dict[icu.UDateTimePatternField, DatetimeFormattedPartTypeT] = {
93
+ icu.UDateFormatField.ERA: "era",
94
+ icu.UDateFormatField.YEAR: "year",
95
+ icu.UDateFormatField.MONTH: "month",
96
+ icu.UDateFormatField.DATE: "day",
97
+ icu.UDateFormatField.HOUR_OF_DAY0: "hour",
98
+ icu.UDateFormatField.HOUR_OF_DAY1: "hour",
99
+ icu.UDateFormatField.MINUTE: "minute",
100
+ icu.UDateFormatField.SECOND: "second",
101
+ icu.UDateFormatField.FRACTIONAL_SECOND: "fraction_second_digits",
102
+ icu.UDateFormatField.DAY_OF_WEEK: "weekday",
103
+ icu.UDateFormatField.AM_PM: "day_period",
104
+ icu.UDateFormatField.HOUR1: "hour",
105
+ icu.UDateFormatField.HOUR0: "hour",
106
+ icu.UDateFormatField.TIMEZONE: "time_zone_name",
107
+ icu.UDateFormatField.EXTENDED_YEAR: "year",
108
+ icu.UDateFormatField.TIMEZONE_RFC: "time_zone_name",
109
+ icu.UDateFormatField.TIMEZONE_GENERIC: "time_zone_name",
110
+ icu.UDateFormatField.STANDALONE_DAY: "weekday",
111
+ icu.UDateFormatField.STANDALONE_MONTH: "month",
112
+ icu.UDateFormatField.TIMEZONE_SPECIAL: "time_zone_name",
113
+ icu.UDateFormatField.YEAR_NAME: "year",
114
+ icu.UDateFormatField.AM_PM_MIDNIGHT_NOON: "day_period",
115
+ icu.UDateFormatField.FLEXIBLE_DAY_PERIOD: "day_period",
116
+ }
117
+ _ICU_HOUR_CYCLE_TO_HOUR_CYCLE: dict[icu.UDateTimePatternField, HourCycleT] = {
118
+ icu.UDateFormatHourCycle.HOUR_CYCLE_11: "h11",
119
+ icu.UDateFormatHourCycle.HOUR_CYCLE_12: "h12",
120
+ icu.UDateFormatHourCycle.HOUR_CYCLE_23: "h23",
121
+ icu.UDateFormatHourCycle.HOUR_CYCLE_24: "h24",
113
122
  }
114
123
  _PATTERN_QUOTE = "'"
115
124
 
@@ -172,7 +181,10 @@ class DateTimeFormatOptions:
172
181
  }
173
182
 
174
183
 
175
- def _options_to_possible_skeletons(options: DateTimeFormatOptions) -> Iterable[str]:
184
+ def _options_to_possible_skeletons( # noqa: PLR0912, PLR0915
185
+ generator: icu.DateTimePatternGenerator,
186
+ options: DateTimeFormatOptions,
187
+ ) -> Iterable[str]:
176
188
  skeleton_parts: list[str | tuple[str, ...]] = []
177
189
 
178
190
  # Note: The parts should be ordered from big to small.
@@ -225,35 +237,39 @@ def _options_to_possible_skeletons(options: DateTimeFormatOptions) -> Iterable[s
225
237
  case "narrow":
226
238
  skeleton_parts.append("BBBBB")
227
239
 
228
- match (options.hour_cycle, options.hour12, options.hour):
229
- case ("h11", _, "numeric"):
230
- skeleton_parts.append(("aK", "K"))
231
- case ("h11", _, "2-digit"):
232
- skeleton_parts.append(("aKK", "KK"))
233
- case ("h12", _, "numeric"):
234
- skeleton_parts.append(("ah", "h"))
235
- case ("h12", _, "2-digit"):
236
- skeleton_parts.append(("ahh", "hh"))
237
- case ("h23", _, "numeric"):
240
+ hour_cycle = options.hour_cycle
241
+ if not hour_cycle:
242
+ if options.hour and not options.hour12:
243
+ hour_cycle = _ICU_HOUR_CYCLE_TO_HOUR_CYCLE[generator.getDefaultHourCycle()]
244
+ elif options.hour12 is not None:
245
+ match (options.hour12, generator.getDefaultHourCycle()):
246
+ case (True, icu.UDateFormatHourCycle.HOUR_CYCLE_11):
247
+ hour_cycle = "h11"
248
+ case (True, icu.UDateFormatHourCycle.HOUR_CYCLE_12):
249
+ hour_cycle = "h12"
250
+ case (True, icu.UDateFormatHourCycle.HOUR_CYCLE_23):
251
+ hour_cycle = "h11"
252
+ case (True, icu.UDateFormatHourCycle.HOUR_CYCLE_24):
253
+ hour_cycle = "h12"
254
+ case (False, _):
255
+ hour_cycle = "h23"
256
+ match (hour_cycle, options.hour):
257
+ case ("h11", "numeric"):
258
+ skeleton_parts.append("K")
259
+ case ("h11", "2-digit"):
260
+ skeleton_parts.append("KK")
261
+ case ("h12", "numeric"):
262
+ skeleton_parts.append("h")
263
+ case ("h12", "2-digit"):
264
+ skeleton_parts.append("hh")
265
+ case ("h23", "numeric"):
238
266
  skeleton_parts.append("H")
239
- case ("h23", _, "2-digit"):
267
+ case ("h23", "2-digit"):
240
268
  skeleton_parts.append("HH")
241
- case ("h24", _, "numeric"):
269
+ case ("h24", "numeric"):
242
270
  skeleton_parts.append("k")
243
- case ("h24", _, "2-digit"):
271
+ case ("h24", "2-digit"):
244
272
  skeleton_parts.append("kk")
245
- case (_, True, "numeric"):
246
- skeleton_parts.append(("ah", "h"))
247
- case (_, True, "2-digit"):
248
- skeleton_parts.append(("ahh", "hh"))
249
- case (_, False, "numeric"):
250
- skeleton_parts.append("H")
251
- case (_, False, "2-digit"):
252
- skeleton_parts.append("HH")
253
- case (_, _, "numeric"):
254
- skeleton_parts.append("j")
255
- case (_, _, "2-digit"):
256
- skeleton_parts.append(("jj", "j"))
257
273
 
258
274
  match options.minute:
259
275
  case "numeric":
@@ -304,17 +320,18 @@ class _MatchedFormatPattern:
304
320
  skeleton: str
305
321
  pattern: str
306
322
 
323
+ @override
307
324
  def __str__(self) -> str:
308
325
  return self.pattern
309
326
 
310
327
 
311
- class FormatPatternNotFoundException(Exception):
328
+ class FormatPatternNotFoundError(Exception):
312
329
  pass
313
330
 
314
331
 
315
332
  @dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
316
- class DateTimePatternPart:
317
- type: DatetimePatternPartTypeT
333
+ class DateTimeFormattedPart:
334
+ type: DatetimeFormattedPartTypeT
318
335
  value: str
319
336
  _pattern: str | None = None
320
337
 
@@ -327,8 +344,8 @@ class DateTimePatternPart:
327
344
 
328
345
 
329
346
  @dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
330
- class DateTimeIntervalPatternPart:
331
- type: DatetimePatternPartTypeT
347
+ class DateTimeIntervalFormattedPart:
348
+ type: DatetimeFormattedPartTypeT
332
349
  value: str
333
350
  source: Literal["start_range", "end_range", "shared"]
334
351
 
@@ -340,14 +357,11 @@ class DateTimeIntervalPatternPart:
340
357
  }
341
358
 
342
359
 
343
- @cache
344
360
  def _options_to_format_pattern(
345
- locale: icu.Locale, # ty: ignore[unresolved-attribute]
361
+ generator: icu.DateTimePatternGenerator,
346
362
  options: DateTimeFormatOptions,
347
363
  ) -> _MatchedFormatPattern:
348
- possible_skeletons = list(_options_to_possible_skeletons(options))
349
-
350
- generator = icu.DateTimePatternGenerator.createInstance(locale) # ty: ignore[unresolved-attribute]
364
+ possible_skeletons = list(_options_to_possible_skeletons(generator, options))
351
365
 
352
366
  # Try a perfect match
353
367
  for skeleton in possible_skeletons:
@@ -368,7 +382,8 @@ def _options_to_format_pattern(
368
382
  pattern=pattern,
369
383
  )
370
384
 
371
- raise FormatPatternNotFoundException("Didn't find pattern for desired options")
385
+ error = "Didn't find pattern for desired options"
386
+ raise FormatPatternNotFoundError(error)
372
387
 
373
388
 
374
389
  @dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
@@ -381,7 +396,7 @@ class _PartSpan:
381
396
  return cls(start=0, end=0)
382
397
 
383
398
  @classmethod
384
- def from_constrained_fieldposition(cls, position: icu.ConstrainedFieldPosition) -> _PartSpan: # ty: ignore[unresolved-attribute]
399
+ def from_constrained_fieldposition(cls, position: icu.ConstrainedFieldPosition) -> _PartSpan:
385
400
  return cls(start=position.getStart(), end=position.getLimit())
386
401
 
387
402
  def __contains__(self, inner: _PartSpan) -> bool:
@@ -408,22 +423,31 @@ class DateTimeFormat:
408
423
  else:
409
424
  self.options = DateTimeFormatOptions(**options)
410
425
 
426
+ @cached_property
427
+ def _icu_datetime_pattern_generator(self) -> icu.DateTimePatternGenerator:
428
+ return icu.DateTimePatternGenerator.createInstance(self.locale._icu_locale)
429
+
411
430
  @cached_property
412
431
  def _matched_pattern(self) -> _MatchedFormatPattern:
413
- return _options_to_format_pattern(self.locale._icu_locale, self.options)
432
+ return _options_to_format_pattern(self._icu_datetime_pattern_generator, self.options)
414
433
 
415
434
  @cached_property
416
435
  def _icu_pattern(self) -> str:
417
436
  return self._matched_pattern.pattern
418
437
 
419
438
  @cached_property
420
- def _icu_date_format(self) -> icu.SimpleDateFormat: # ty: ignore[unresolved-attribute]
421
- return icu.SimpleDateFormat(self._icu_pattern, self.locale._icu_locale) # ty: ignore[unresolved-attribute]
439
+ def _icu_date_format(self) -> icu.SimpleDateFormat:
440
+ return icu.SimpleDateFormat(self._icu_pattern, self.locale._icu_locale)
422
441
 
423
442
  def format(self, datetime_: dt.datetime, /) -> str:
424
443
  return self._icu_date_format.format(datetime_)
425
444
 
426
- def format_to_parts(self, datetime_: dt.datetime, /) -> Iterable[DateTimePatternPart]:
445
+ def format_to_parts(self, datetime_: dt.datetime, /) -> Iterable[DateTimeFormattedPart]:
446
+ # Sadly there is no formatToValue() function available inside the SimpleDateFormat class
447
+ # ICU provides (formatToValue() could return a "formatted" object one could iterate
448
+ # over to get the different parts). This means we need to parse the pattern ourselved here
449
+ # and create the parts ourselves. Luckily we can adapt the ICU code for parsing the pattern
450
+ # easily and thus still have a relatively sane implementation.
427
451
  # Based on https://github.com/unicode-org/icu/blob/6fb634d81d10dd4667fb3fbcd1f19d9b9b926e62/icu4c/source/i18n/smpdtfmt.cpp#L1060
428
452
  pattern = self._icu_pattern
429
453
  in_quote = False
@@ -436,9 +460,9 @@ class DateTimeFormat:
436
460
  char = pattern[i]
437
461
 
438
462
  if char != prev_char and count > 0:
439
- yield DateTimePatternPart(
463
+ yield DateTimeFormattedPart(
440
464
  type=_PATTERN_SYMBOL_TO_TYPE.get(prev_char, "unknown"),
441
- value=icu.SimpleDateFormat(prev_char * count, self.locale._icu_locale).format(datetime_), # ty: ignore[unresolved-attribute]
465
+ value=icu.SimpleDateFormat(prev_char * count, self.locale._icu_locale).format(datetime_),
442
466
  _pattern=prev_char * count,
443
467
  )
444
468
  count = 0
@@ -451,7 +475,7 @@ class DateTimeFormat:
451
475
  in_quote = not in_quote
452
476
  elif not in_quote and char in _PATTERN_SYMBOLS:
453
477
  if literal_chars:
454
- yield DateTimePatternPart(
478
+ yield DateTimeFormattedPart(
455
479
  type="literal",
456
480
  value="".join(literal_chars),
457
481
  )
@@ -464,44 +488,46 @@ class DateTimeFormat:
464
488
  i += 1
465
489
 
466
490
  if count > 0:
467
- yield DateTimePatternPart(
491
+ yield DateTimeFormattedPart(
468
492
  type=_PATTERN_SYMBOL_TO_TYPE.get(prev_char, "unknown"),
469
- value=icu.SimpleDateFormat(prev_char * count, self.locale._icu_locale).format(datetime_), # ty: ignore[unresolved-attribute]
493
+ value=icu.SimpleDateFormat(prev_char * count, self.locale._icu_locale).format(datetime_),
470
494
  _pattern=prev_char * count,
471
495
  )
472
496
  assert not literal_chars # noqa: S101
473
497
  elif literal_chars:
474
- yield DateTimePatternPart(
498
+ yield DateTimeFormattedPart(
475
499
  type="literal",
476
500
  value="".join(literal_chars),
477
501
  )
478
502
 
479
503
  @cached_property
480
- def _icu_dateinterval_format(self) -> icu.DateIntervalFormat: # ty: ignore[unresolved-attribute]
481
- possible_skeletons = list(_options_to_possible_skeletons(self.options))
482
- return icu.DateIntervalFormat.createInstance(possible_skeletons[0], self.locale._icu_locale) # ty: ignore[unresolved-attribute]
504
+ def _icu_dateinterval_format(self) -> icu.DateIntervalFormat:
505
+ possible_skeletons = list(
506
+ _options_to_possible_skeletons(self._icu_datetime_pattern_generator, self.options),
507
+ )
508
+ return icu.DateIntervalFormat.createInstance(possible_skeletons[0], self.locale._icu_locale)
483
509
 
484
510
  def format_range(
485
511
  self,
486
512
  start_datetime: dt.datetime,
487
513
  end_datetime: dt.datetime,
488
514
  ) -> str:
489
- icu_date_interval = icu.DateInterval(start_datetime, end_datetime) # ty: ignore[unresolved-attribute]
515
+ icu_date_interval = icu.DateInterval(start_datetime, end_datetime)
490
516
  return self._icu_dateinterval_format.format(icu_date_interval)
491
517
 
492
518
  def format_range_to_parts(
493
519
  self,
494
520
  start_datetime: dt.datetime,
495
521
  end_datetime: dt.datetime,
496
- ) -> Iterable[DateTimeIntervalPatternPart]:
497
- icu_date_interval = icu.DateInterval(start_datetime, end_datetime) # ty: ignore[unresolved-attribute]
522
+ ) -> Iterable[DateTimeIntervalFormattedPart]:
523
+ icu_date_interval = icu.DateInterval(start_datetime, end_datetime)
498
524
  formatted = self._icu_dateinterval_format.formatToValue(icu_date_interval)
499
525
 
500
526
  # Find spans of both datetimes (used to determine which parts have which source)
501
527
  span_start = _PartSpan.empty()
502
528
  span_end = _PartSpan.empty()
503
529
  for part in formatted:
504
- if part.getCategory() == icu.UFieldCategory.DATE_INTERVAL_SPAN: # ty: ignore[unresolved-attribute]
530
+ if part.getCategory() == icu.UFieldCategory.DATE_INTERVAL_SPAN:
505
531
  match part.getField():
506
532
  case 0:
507
533
  span_start = _PartSpan.from_constrained_fieldposition(part)
@@ -522,14 +548,14 @@ class DateTimeFormat:
522
548
  for part in formatted:
523
549
  span = _PartSpan.from_constrained_fieldposition(part)
524
550
  if span.start > last_end:
525
- yield DateTimeIntervalPatternPart(
551
+ yield DateTimeIntervalFormattedPart(
526
552
  type="literal",
527
553
  value=result_string[last_end:span.start],
528
554
  source=source_of(_PartSpan(start=last_end, end=span.start)),
529
555
  )
530
556
 
531
- if part.getCategory() == icu.UFieldCategory.DATE: # ty: ignore[unresolved-attribute]
532
- yield DateTimeIntervalPatternPart(
557
+ if part.getCategory() == icu.UFieldCategory.DATE:
558
+ yield DateTimeIntervalFormattedPart(
533
559
  type=_PATTERN_FIELD_TO_TYPE.get(part.getField(), "unknown"),
534
560
  value=result_string[span.start:span.end],
535
561
  source=source_of(span),
@@ -539,7 +565,7 @@ class DateTimeFormat:
539
565
 
540
566
  # Ensure we didn't miss anything at the end
541
567
  if last_end < len(result_string):
542
- yield DateTimeIntervalPatternPart(
568
+ yield DateTimeIntervalFormattedPart(
543
569
  type="literal",
544
570
  value=result_string[last_end:],
545
571
  source=source_of(_PartSpan(start=last_end, end=len(result_string))),
python_intl/locale.py CHANGED
@@ -2,7 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  from functools import cached_property
4
4
 
5
- import icu # type: ignore[import-untyped]
5
+ import icu
6
6
 
7
7
 
8
8
  class Locale:
@@ -12,5 +12,5 @@ class Locale:
12
12
  self.tag = tag
13
13
 
14
14
  @cached_property
15
- def _icu_locale(self) -> icu.Locale: # ty: ignore[unresolved-attribute]
16
- return icu.Locale(self.tag) # ty: ignore[unresolved-attribute]
15
+ def _icu_locale(self) -> icu.Locale:
16
+ return icu.Locale(self.tag)
@@ -0,0 +1,191 @@
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import decimal
5
+ from functools import cached_property
6
+ from typing import TYPE_CHECKING
7
+
8
+ import icu
9
+
10
+ from .locale import Locale
11
+
12
+ if TYPE_CHECKING:
13
+ from typing import NotRequired, TypedDict
14
+
15
+ from ._types import (
16
+ CurrencyDisplayT,
17
+ CurrencySignT,
18
+ CurrencyT,
19
+ LocaleMatcherT,
20
+ StyleT,
21
+ UnitDisplayT,
22
+ UnitT,
23
+ )
24
+
25
+ type NumberT = decimal.Decimal | float | int
26
+
27
+ # Important: Must be the same as DateTimeFormatOptions
28
+ # (nothing is required, as this will be used to construct a
29
+ # DateTimeFormatOptions instance, so default values apply then)
30
+ class NumberFormatOptionsDictT(TypedDict):
31
+ locale_matcher: NotRequired[LocaleMatcherT]
32
+
33
+ style: NotRequired[StyleT]
34
+
35
+ currency: NotRequired[CurrencyT]
36
+ currency_display: NotRequired[CurrencyDisplayT]
37
+ currency_sign: NotRequired[CurrencySignT]
38
+
39
+ unit: NotRequired[UnitT]
40
+ unit_display: NotRequired[UnitDisplayT]
41
+
42
+
43
+ _CURRENCY_DISPLAY_TO_JSON_MAP: dict[str, str] = {
44
+ "narrow_symbol": "narrowSymbol",
45
+ }
46
+
47
+
48
+ class InvalidNumberFormatOptionError(ValueError):
49
+ pass
50
+
51
+
52
+ @dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
53
+ class NumberFormatOptions:
54
+ locale_matcher: LocaleMatcherT = "best fit"
55
+
56
+ style: StyleT = "decimal"
57
+
58
+ currency: CurrencyT | None = None
59
+ currency_display: CurrencyDisplayT = "symbol"
60
+ currency_sign: CurrencySignT = "standard"
61
+
62
+ unit: UnitT | None = None
63
+ unit_display: UnitDisplayT = "short"
64
+
65
+ def __post_init__(self) -> None:
66
+ error = None
67
+ if self.style == "currency" and self.currency is None:
68
+ error = "You need to provide a currency when using the currency style"
69
+ elif self.style == "unit" and self.unit is None:
70
+ error = "You need to provide a unit when using the unit style"
71
+
72
+ if error:
73
+ raise InvalidNumberFormatOptionError(error)
74
+
75
+ def to_json(self) -> dict[str, str | int]:
76
+ return {
77
+ k: v
78
+ for k, v in (
79
+ ("localeMatcher", self.locale_matcher),
80
+
81
+ ("style", self.style),
82
+
83
+ ("currency", self.currency),
84
+ ("currencyDisplay", _CURRENCY_DISPLAY_TO_JSON_MAP.get(
85
+ self.currency_display,
86
+ self.currency_display,
87
+ )),
88
+ ("currencySign", self.currency_sign),
89
+
90
+ ("unit", self.unit),
91
+ ("unitDisplay", self.unit_display),
92
+ )
93
+ if v is not None
94
+ }
95
+
96
+
97
+ def _options_to_skeleton(options: NumberFormatOptions) -> str:
98
+ skeleton_parts: list[str] = []
99
+
100
+ match options.style:
101
+ case "decimal":
102
+ skeleton_parts.append("decimal-auto")
103
+ case "percent":
104
+ skeleton_parts.append("precision-integer")
105
+ skeleton_parts.append("scale/100")
106
+ skeleton_parts.append("percent")
107
+ case "currency":
108
+ skeleton_parts.append(f"currency/{options.currency}")
109
+ skeleton_parts.append("precision-currency-standard")
110
+ if options.currency_sign == "accounting":
111
+ skeleton_parts.append("sign-accounting")
112
+ match options.currency_display:
113
+ case "code":
114
+ skeleton_parts.append("unit-width-iso-code")
115
+ case "symbol":
116
+ skeleton_parts.append("unit-width-short")
117
+ case "narrow_symbol":
118
+ skeleton_parts.append("unit-width-narrow")
119
+ case "name":
120
+ skeleton_parts.append("unit-width-full-name")
121
+ case "unit":
122
+ skeleton_parts.append(f"unit/{options.unit}")
123
+ match options.unit_display:
124
+ case "short":
125
+ skeleton_parts.append("unit-width-short")
126
+ case "narrow":
127
+ skeleton_parts.append("unit-width-narrow")
128
+ case "long":
129
+ skeleton_parts.append("unit-width-full-name")
130
+
131
+ return " ".join(skeleton_parts)
132
+
133
+
134
+ class NumberFormat:
135
+ locale: Locale
136
+ options: NumberFormatOptions
137
+
138
+ def __init__(
139
+ self,
140
+ locale: Locale | str,
141
+ options: NumberFormatOptions | NumberFormatOptionsDictT | None = None,
142
+ ) -> None:
143
+ if isinstance(locale, Locale):
144
+ self.locale = locale
145
+ else:
146
+ self.locale = Locale(locale)
147
+ if options is None:
148
+ self.options = NumberFormatOptions()
149
+ elif isinstance(options, NumberFormatOptions):
150
+ self.options = options
151
+ else:
152
+ self.options = NumberFormatOptions(**options)
153
+
154
+ @cached_property
155
+ def _icu_number_formatter(self) -> icu.LocalizedNumberFormatter:
156
+ skeleton = _options_to_skeleton(self.options)
157
+ return icu.NumberFormatter.forSkeleton(skeleton).locale(self.locale._icu_locale)
158
+
159
+ def format(self, value: NumberT, /) -> str:
160
+ match value:
161
+ case int():
162
+ return self._icu_number_formatter.formatInt(value)
163
+ case float():
164
+ return self._icu_number_formatter.formatDouble(value)
165
+ case decimal.Decimal():
166
+ return self._icu_number_formatter.formatDecimal(str(value).encode("ascii"))
167
+
168
+ @cached_property
169
+ def _icu_number_range_formatter(self) -> icu.LocalizedNumberRangeFormatter:
170
+ skeleton = _options_to_skeleton(self.options)
171
+ return (
172
+ icu.NumberRangeFormatter
173
+ .withLocale(self.locale._icu_locale)
174
+ .numberFormatterBoth(icu.NumberFormatter.forSkeleton(skeleton))
175
+ )
176
+
177
+ def format_range(self, start_value: NumberT, end_value: NumberT, /) -> str:
178
+ match start_value, end_value:
179
+ case int(), int():
180
+ return self._icu_number_range_formatter.formatIntRange(start_value, end_value)
181
+ case float(), float():
182
+ return self._icu_number_range_formatter.formatDoubleRange(start_value, end_value)
183
+ case decimal.Decimal(), decimal.Decimal():
184
+ return self._icu_number_range_formatter.formatDoubleRange(
185
+ # For some reason formatDecimalRange fails, so we fall back to floats
186
+ float(start_value),
187
+ float(end_value),
188
+ )
189
+ case _:
190
+ error = "Both parameters passed to format_range must have the same type"
191
+ raise ValueError(error)
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-intl
3
- Version: 0.8.0
3
+ Version: 0.10.0
4
4
  Summary: Python implementation of the Intl JavaScript API
5
5
  Author: David Danier
6
6
  Author-email: David Danier <david.danier@gmail.com>
7
7
  License-Expression: MIT
8
8
  License-File: LICENSE
9
- Requires-Dist: pyicu>=2.16.2
9
+ Requires-Dist: pyicu>=2.17.0
10
10
  Requires-Python: >=3.12
11
11
  Project-URL: Repository, https://github.com/ddanier/python-intl
12
12
  Description-Content-Type: text/markdown
@@ -62,7 +62,7 @@ Intl.DateTimeFormatOptions(time_zone_name="short_offset").to_json()
62
62
  import datetime as dt
63
63
  import python_intl as Intl
64
64
 
65
- locale = Intl.DateTimeFormat("de-DE")
65
+ locale = Intl.Locale("de-DE")
66
66
  ```
67
67
 
68
68
  #### Compatibility
@@ -71,6 +71,38 @@ locale = Intl.DateTimeFormat("de-DE")
71
71
  allow using the locale class instead of a string with the other classes. There will
72
72
  be more later.
73
73
 
74
+ ### `Intl.NumberFormat`
75
+
76
+ #### Example usage
77
+
78
+ ```python
79
+ import python_intl as Intl
80
+
81
+ # Format liters
82
+ number = 1234.567
83
+ formatter = Intl.NumberFormat("de-DE", {"style": "unit", "unit": "liter"})
84
+ formatter.format(number)
85
+ # Result = "1.234,567 l"
86
+
87
+ # Format euros
88
+ number = 1234.567
89
+ formatter = Intl.NumberFormat("de-DE", {"style": "currency", "currency": "EUR"})
90
+ formatter.format(number)
91
+ # Result = "1.234,57 €"
92
+ # Note: Result will be automatically rounded to two decimal places, as EUR defines.
93
+ ```
94
+
95
+ #### Compatibility
96
+
97
+ | Method | Status | Python name |
98
+ | --------------------------------- | :----: | ------------------------------------ |
99
+ | `NumberFormat.format` | ✅ | |
100
+ | `NumberFormat.formatToParts` | ❌ | `NumberFormat.format_to_parts` |
101
+ | `NumberFormat.supportedLocalesOf` | ❌ | |
102
+ | `NumberFormat.formatRange` | ✅ | `NumberFormat.format_range` |
103
+ | `NumberFormat.formatRangeToParts` | ❌ | `NumberFormat.format_range_to_parts` |
104
+ | `NumberFormat.resolvedOptions` | ❌ | |
105
+
74
106
  ### `Intl.DateTimeFormat`
75
107
 
76
108
  #### Example usage
@@ -138,7 +170,8 @@ Be sure to be able to install `PyICU`, see the installation docs there:
138
170
  https://gitlab.pyicu.org/main/pyicu#installing-pyicu
139
171
 
140
172
  **Hint:** I mainly did run into issues with `pkg-config` not finding the ICU library,
141
- setting `PKG_CONFIG_PATH` accordingly helps most of the time I guess.
173
+ setting `PKG_CONFIG_PATH` accordingly helps most of the time I guess. See [`.envrc`](.envrc)
174
+ for how to set this up correctly on `nix` based systems.
142
175
 
143
176
  When this is done you should be able to install `python-intl` using any package
144
177
  manager, like `pip install python-intl` or `uv add python-intl`.
@@ -151,4 +184,5 @@ are unsure about whether your changes really suits the project please create an
151
184
  issue first, to talk about this.
152
185
 
153
186
  Please do not contribute AI generated code unless we explicitly talked about
154
- this and agreed upon doing so first. In general I do not want AI contributions.
187
+ this and agreed upon doing so first. In general I do not want vibe coded
188
+ contributions.
@@ -0,0 +1,10 @@
1
+ python_intl/__init__.py,sha256=zPOZ9CG3qQEKiYoWuclgHnsYDmb_APGLPThlstTSxoo,578
2
+ python_intl/_types.py,sha256=3mdXF8XjwlP-79zu689TzfAM3oTuq1N-P1OW0drT60k,2803
3
+ python_intl/collator.py,sha256=80IjM9mYsSPmjLsi-bo3sg5wDidjnNPCiNayKXdHIic,4839
4
+ python_intl/datetimeformat.py,sha256=gXnARf_29k25rIXOnQm2roq0s0mi5rhVvFpixVy-Lx8,19836
5
+ python_intl/locale.py,sha256=QwgtSAOql8UKLEO6kR5WrtG05XX5-DOB75OwPJY8sBc,280
6
+ python_intl/numberformat.py,sha256=VAO1vbkMGVhZiqjE9dn72KlKwclQNCCwEScRMXELMXs,6502
7
+ python_intl-0.10.0.dist-info/licenses/LICENSE,sha256=vBhn8BZCY-G3D6-ca99f4FU3ggdJSrKBTa3Yk8ZIAN8,1078
8
+ python_intl-0.10.0.dist-info/WHEEL,sha256=3NO1oYsF7mANFUWVdyEQLM-zmecczWWEmmF5rEbXrWk,80
9
+ python_intl-0.10.0.dist-info/METADATA,sha256=SR4UgtG-k2KIybi1TIkflDMKCAURvzMYQ2YyAjjesQ8,6861
10
+ python_intl-0.10.0.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: uv 0.12.6
2
+ Generator: uv 0.13.6
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -1,9 +0,0 @@
1
- python_intl/__init__.py,sha256=FGTD4uTh9ab-KmIWX_aVfNr7jDhPjZYp0sdiaGP7hQY,396
2
- python_intl/_types.py,sha256=ABKMi2iGjsWzNIBiXObv4sLkPSSQn-1tewsZrJm4lQA,1266
3
- python_intl/collator.py,sha256=Dl8lG20BM9Q_BoFlxWv5aZL1vP1LYI6W0uSC-dtS9tQ,5360
4
- python_intl/datetimeformat.py,sha256=2SGf1EKLTpisf43_1HNoX7Ywv4MxU_pMK2kTqqmyosc,19321
5
- python_intl/locale.py,sha256=p049uArF3SQP9MDBFazzfr2iAfsQE6CpijpMjvsdhmg,384
6
- python_intl-0.8.0.dist-info/licenses/LICENSE,sha256=vBhn8BZCY-G3D6-ca99f4FU3ggdJSrKBTa3Yk8ZIAN8,1078
7
- python_intl-0.8.0.dist-info/WHEEL,sha256=Lkz__M3n3EKWmzMwHnFILNW2SHO43bOxmbqnBjwb--4,80
8
- python_intl-0.8.0.dist-info/METADATA,sha256=shaolN4e5O995stZ_OdkhXDRIJUqMmpzTvG_-qBTz9s,5567
9
- python_intl-0.8.0.dist-info/RECORD,,