python-intl 0.9.0__tar.gz → 0.11.0__tar.gz

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.
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-intl
3
- Version: 0.9.0
3
+ Version: 0.11.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
@@ -97,7 +97,7 @@ formatter.format(number)
97
97
  | Method | Status | Python name |
98
98
  | --------------------------------- | :----: | ------------------------------------ |
99
99
  | `NumberFormat.format` | ✅ | |
100
- | `NumberFormat.formatToParts` | ❌ | `NumberFormat.format_to_parts` |
100
+ | `NumberFormat.formatToParts` | ✅ | `NumberFormat.format_to_parts` |
101
101
  | `NumberFormat.supportedLocalesOf` | ❌ | |
102
102
  | `NumberFormat.formatRange` | ✅ | `NumberFormat.format_range` |
103
103
  | `NumberFormat.formatRangeToParts` | ❌ | `NumberFormat.format_range_to_parts` |
@@ -184,4 +184,5 @@ are unsure about whether your changes really suits the project please create an
184
184
  issue first, to talk about this.
185
185
 
186
186
  Please do not contribute AI generated code unless we explicitly talked about
187
- 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.
@@ -84,7 +84,7 @@ formatter.format(number)
84
84
  | Method | Status | Python name |
85
85
  | --------------------------------- | :----: | ------------------------------------ |
86
86
  | `NumberFormat.format` | ✅ | |
87
- | `NumberFormat.formatToParts` | ❌ | `NumberFormat.format_to_parts` |
87
+ | `NumberFormat.formatToParts` | ✅ | `NumberFormat.format_to_parts` |
88
88
  | `NumberFormat.supportedLocalesOf` | ❌ | |
89
89
  | `NumberFormat.formatRange` | ✅ | `NumberFormat.format_range` |
90
90
  | `NumberFormat.formatRangeToParts` | ❌ | `NumberFormat.format_range_to_parts` |
@@ -171,4 +171,5 @@ are unsure about whether your changes really suits the project please create an
171
171
  issue first, to talk about this.
172
172
 
173
173
  Please do not contribute AI generated code unless we explicitly talked about
174
- this and agreed upon doing so first. In general I do not want AI contributions.
174
+ this and agreed upon doing so first. In general I do not want vibe coded
175
+ contributions.
@@ -1,12 +1,12 @@
1
1
  [project]
2
2
  name = "python-intl"
3
- version = "0.9.0"
3
+ version = "0.11.0"
4
4
  description = "Python implementation of the Intl JavaScript API"
5
5
  readme = "README.md"
6
6
  license = "MIT"
7
7
  license-files = ["LICENSE"]
8
8
  requires-python = ">=3.12"
9
- dependencies = ["pyicu>=2.16.2"]
9
+ dependencies = ["pyicu>=2.17.0"]
10
10
 
11
11
  [[project.authors]]
12
12
  name = "David Danier"
@@ -19,6 +19,7 @@ Repository = "https://github.com/ddanier/python-intl"
19
19
  dev = [
20
20
  "basedpyright>=1.40.1",
21
21
  "mypy>=2.3.1",
22
+ "packaging>=26.3",
22
23
  "pylsp-mypy>=0.8.0",
23
24
  "pyright>=1.1.411",
24
25
  "pytest>=9.1.1",
@@ -108,6 +109,8 @@ ignore_missing_imports = true
108
109
  [tool.basedpyright]
109
110
  pythonVersion = "3.12"
110
111
  reportAny = false
112
+ reportExplicitAny = false
113
+ reportUnusedCallResult = false
111
114
  reportMatchNotExhaustive = false
112
115
  reportUnknownLambdaType = false
113
116
  reportPrivateUsage = false
@@ -123,5 +126,5 @@ module-name = "python_intl"
123
126
  module-root = ""
124
127
 
125
128
  [build-system]
126
- requires = ["uv_build>=0.12.3,<0.13.0"]
129
+ requires = ["uv_build>=0.12.3,<0.14.0"]
127
130
  build-backend = "uv_build"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "python-intl"
3
- version = "0.9.0"
3
+ version = "0.11.0"
4
4
  description = "Python implementation of the Intl JavaScript API"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -10,7 +10,7 @@ license = "MIT"
10
10
  license-files = ["LICENSE"]
11
11
  requires-python = ">=3.12"
12
12
  dependencies = [
13
- "pyicu>=2.16.2",
13
+ "pyicu>=2.17.0",
14
14
  ]
15
15
 
16
16
  [project.urls]
@@ -20,6 +20,7 @@ Repository = "https://github.com/ddanier/python-intl"
20
20
  dev = [
21
21
  "basedpyright>=1.40.1",
22
22
  "mypy>=2.3.1",
23
+ "packaging>=26.3",
23
24
  "pylsp-mypy>=0.8.0",
24
25
  "pyright>=1.1.411",
25
26
  "pytest>=9.1.1",
@@ -111,6 +112,8 @@ ignore_missing_imports = true
111
112
  [tool.basedpyright]
112
113
  pythonVersion = "3.12"
113
114
  reportAny = false
115
+ reportExplicitAny = false
116
+ reportUnusedCallResult = false
114
117
  reportMatchNotExhaustive = false
115
118
  reportUnknownLambdaType = false
116
119
  reportPrivateUsage = false
@@ -123,7 +126,7 @@ reportUnknownParameterType = false
123
126
  reportUnknownArgumentType = false
124
127
 
125
128
  [build-system]
126
- requires = ["uv_build>=0.12.3,<0.13.0"]
129
+ requires = ["uv_build>=0.12.3,<0.14.0"]
127
130
  build-backend = "uv_build"
128
131
 
129
132
  [tool.uv.build-backend]
@@ -5,8 +5,8 @@ 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,
8
+ DateTimeFormattedPart as DateTimeFormattedPart,
9
+ DateTimeIntervalFormattedPart as DateTimeIntervalFormattedPart,
10
10
  FormatPatternNotFoundError as FormatPatternNotFoundError,
11
11
  )
12
12
  from .numberformat import (
@@ -0,0 +1,24 @@
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ from typing import TYPE_CHECKING
5
+
6
+ if TYPE_CHECKING:
7
+ import icu
8
+
9
+
10
+ @dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
11
+ class _FormattedPartSpan:
12
+ start: int
13
+ end: int
14
+
15
+ @classmethod
16
+ def empty(cls) -> _FormattedPartSpan:
17
+ return cls(start=0, end=0)
18
+
19
+ @classmethod
20
+ def from_constrained_fieldposition(cls, position: icu.ConstrainedFieldPosition) -> _FormattedPartSpan:
21
+ return cls(start=position.getStart(), end=position.getLimit())
22
+
23
+ def __contains__(self, inner: _FormattedPartSpan) -> bool:
24
+ return inner.start >= self.start and inner.end <= self.end
@@ -1,11 +1,12 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import dataclasses
4
- from functools import cache, cached_property
4
+ from functools import cached_property
5
5
  from typing import TYPE_CHECKING, Literal, override
6
6
 
7
7
  import icu
8
8
 
9
+ from ._utils import _FormattedPartSpan
9
10
  from .locale import Locale
10
11
 
11
12
  if TYPE_CHECKING:
@@ -30,7 +31,7 @@ if TYPE_CHECKING:
30
31
  YearFormatT,
31
32
  )
32
33
 
33
- type DatetimePatternPartTypeT = Literal[
34
+ type DatetimeFormattedPartTypeT = Literal[
34
35
  "literal", "unknown",
35
36
  "era", "year", "month", "weekday", "day", "day_period",
36
37
  "hour", "minute", "second", "fraction_second_digits",
@@ -58,7 +59,7 @@ if TYPE_CHECKING:
58
59
  time_zone_name: NotRequired[TimezoneNameFormatT]
59
60
 
60
61
  _PATTERN_SYMBOLS = "GyYuUrQqMLqQdDFgEecabBhHkKmsSAzZOvVxX" # includes unused
61
- _PATTERN_SYMBOL_TO_TYPE: dict[str, DatetimePatternPartTypeT] = {
62
+ _PATTERN_SYMBOL_TO_TYPE: dict[str, DatetimeFormattedPartTypeT] = {
62
63
  "G": "era",
63
64
  "y": "year",
64
65
  "Y": "year",
@@ -89,27 +90,36 @@ _PATTERN_SYMBOL_TO_TYPE: dict[str, DatetimePatternPartTypeT] = {
89
90
  "x": "time_zone_name",
90
91
  "X": "time_zone_name",
91
92
  }
92
- _PATTERN_FIELD_TO_TYPE: dict[icu.UDateTimePatternField, DatetimePatternPartTypeT] = {
93
- icu.DateFormat.ERA_FIELD: "era",
94
- icu.DateFormat.YEAR_FIELD: "year",
95
- icu.DateFormat.MONTH_FIELD: "month",
96
- icu.DateFormat.DAY_OF_WEEK_FIELD: "weekday",
97
- icu.DateFormat.DATE_FIELD: "day",
98
- icu.DateFormat.AM_PM_FIELD: "day_period",
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",
106
- icu.DateFormat.HOUR1_FIELD: "hour",
107
- icu.DateFormat.HOUR_OF_DAY0_FIELD: "hour",
108
- icu.DateFormat.HOUR_OF_DAY1_FIELD: "hour",
109
- icu.DateFormat.MINUTE_FIELD: "minute",
110
- icu.DateFormat.SECOND_FIELD: "second",
111
- icu.DateFormat.MILLISECOND_FIELD: "fraction_second_digits",
112
- icu.DateFormat.TIMEZONE_FIELD: "time_zone_name",
93
+ _PATTERN_FIELD_TO_TYPE: dict[icu.UDateTimePatternField, DatetimeFormattedPartTypeT] = {
94
+ icu.UDateFormatField.ERA: "era",
95
+ icu.UDateFormatField.YEAR: "year",
96
+ icu.UDateFormatField.MONTH: "month",
97
+ icu.UDateFormatField.DATE: "day",
98
+ icu.UDateFormatField.HOUR_OF_DAY0: "hour",
99
+ icu.UDateFormatField.HOUR_OF_DAY1: "hour",
100
+ icu.UDateFormatField.MINUTE: "minute",
101
+ icu.UDateFormatField.SECOND: "second",
102
+ icu.UDateFormatField.FRACTIONAL_SECOND: "fraction_second_digits",
103
+ icu.UDateFormatField.DAY_OF_WEEK: "weekday",
104
+ icu.UDateFormatField.AM_PM: "day_period",
105
+ icu.UDateFormatField.HOUR1: "hour",
106
+ icu.UDateFormatField.HOUR0: "hour",
107
+ icu.UDateFormatField.TIMEZONE: "time_zone_name",
108
+ icu.UDateFormatField.EXTENDED_YEAR: "year",
109
+ icu.UDateFormatField.TIMEZONE_RFC: "time_zone_name",
110
+ icu.UDateFormatField.TIMEZONE_GENERIC: "time_zone_name",
111
+ icu.UDateFormatField.STANDALONE_DAY: "weekday",
112
+ icu.UDateFormatField.STANDALONE_MONTH: "month",
113
+ icu.UDateFormatField.TIMEZONE_SPECIAL: "time_zone_name",
114
+ icu.UDateFormatField.YEAR_NAME: "year",
115
+ icu.UDateFormatField.AM_PM_MIDNIGHT_NOON: "day_period",
116
+ icu.UDateFormatField.FLEXIBLE_DAY_PERIOD: "day_period",
117
+ }
118
+ _ICU_HOUR_CYCLE_TO_HOUR_CYCLE: dict[icu.UDateTimePatternField, HourCycleT] = {
119
+ icu.UDateFormatHourCycle.HOUR_CYCLE_11: "h11",
120
+ icu.UDateFormatHourCycle.HOUR_CYCLE_12: "h12",
121
+ icu.UDateFormatHourCycle.HOUR_CYCLE_23: "h23",
122
+ icu.UDateFormatHourCycle.HOUR_CYCLE_24: "h24",
113
123
  }
114
124
  _PATTERN_QUOTE = "'"
115
125
 
@@ -172,7 +182,10 @@ class DateTimeFormatOptions:
172
182
  }
173
183
 
174
184
 
175
- def _options_to_possible_skeletons(options: DateTimeFormatOptions) -> Iterable[str]: # noqa: PLR0912, PLR0915
185
+ def _options_to_possible_skeletons( # noqa: PLR0912, PLR0915
186
+ generator: icu.DateTimePatternGenerator,
187
+ options: DateTimeFormatOptions,
188
+ ) -> Iterable[str]:
176
189
  skeleton_parts: list[str | tuple[str, ...]] = []
177
190
 
178
191
  # Note: The parts should be ordered from big to small.
@@ -225,35 +238,39 @@ def _options_to_possible_skeletons(options: DateTimeFormatOptions) -> Iterable[s
225
238
  case "narrow":
226
239
  skeleton_parts.append("BBBBB")
227
240
 
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"):
241
+ hour_cycle = options.hour_cycle
242
+ if not hour_cycle:
243
+ if options.hour and not options.hour12:
244
+ hour_cycle = _ICU_HOUR_CYCLE_TO_HOUR_CYCLE[generator.getDefaultHourCycle()]
245
+ elif options.hour12 is not None:
246
+ match (options.hour12, generator.getDefaultHourCycle()):
247
+ case (True, icu.UDateFormatHourCycle.HOUR_CYCLE_11):
248
+ hour_cycle = "h11"
249
+ case (True, icu.UDateFormatHourCycle.HOUR_CYCLE_12):
250
+ hour_cycle = "h12"
251
+ case (True, icu.UDateFormatHourCycle.HOUR_CYCLE_23):
252
+ hour_cycle = "h11"
253
+ case (True, icu.UDateFormatHourCycle.HOUR_CYCLE_24):
254
+ hour_cycle = "h12"
255
+ case (False, _):
256
+ hour_cycle = "h23"
257
+ match (hour_cycle, options.hour):
258
+ case ("h11", "numeric"):
259
+ skeleton_parts.append("K")
260
+ case ("h11", "2-digit"):
261
+ skeleton_parts.append("KK")
262
+ case ("h12", "numeric"):
263
+ skeleton_parts.append("h")
264
+ case ("h12", "2-digit"):
265
+ skeleton_parts.append("hh")
266
+ case ("h23", "numeric"):
238
267
  skeleton_parts.append("H")
239
- case ("h23", _, "2-digit"):
268
+ case ("h23", "2-digit"):
240
269
  skeleton_parts.append("HH")
241
- case ("h24", _, "numeric"):
270
+ case ("h24", "numeric"):
242
271
  skeleton_parts.append("k")
243
- case ("h24", _, "2-digit"):
272
+ case ("h24", "2-digit"):
244
273
  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
274
 
258
275
  match options.minute:
259
276
  case "numeric":
@@ -314,8 +331,8 @@ class FormatPatternNotFoundError(Exception):
314
331
 
315
332
 
316
333
  @dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
317
- class DateTimePatternPart:
318
- type: DatetimePatternPartTypeT
334
+ class DateTimeFormattedPart:
335
+ type: DatetimeFormattedPartTypeT
319
336
  value: str
320
337
  _pattern: str | None = None
321
338
 
@@ -328,8 +345,8 @@ class DateTimePatternPart:
328
345
 
329
346
 
330
347
  @dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
331
- class DateTimeIntervalPatternPart:
332
- type: DatetimePatternPartTypeT
348
+ class DateTimeIntervalFormattedPart:
349
+ type: DatetimeFormattedPartTypeT
333
350
  value: str
334
351
  source: Literal["start_range", "end_range", "shared"]
335
352
 
@@ -341,14 +358,11 @@ class DateTimeIntervalPatternPart:
341
358
  }
342
359
 
343
360
 
344
- @cache
345
361
  def _options_to_format_pattern(
346
- locale: icu.Locale,
362
+ generator: icu.DateTimePatternGenerator,
347
363
  options: DateTimeFormatOptions,
348
364
  ) -> _MatchedFormatPattern:
349
- possible_skeletons = list(_options_to_possible_skeletons(options))
350
-
351
- generator = icu.DateTimePatternGenerator.createInstance(locale)
365
+ possible_skeletons = list(_options_to_possible_skeletons(generator, options))
352
366
 
353
367
  # Try a perfect match
354
368
  for skeleton in possible_skeletons:
@@ -373,23 +387,6 @@ def _options_to_format_pattern(
373
387
  raise FormatPatternNotFoundError(error)
374
388
 
375
389
 
376
- @dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
377
- class _PartSpan:
378
- start: int
379
- end: int
380
-
381
- @classmethod
382
- def empty(cls) -> _PartSpan:
383
- return cls(start=0, end=0)
384
-
385
- @classmethod
386
- def from_constrained_fieldposition(cls, position: icu.ConstrainedFieldPosition) -> _PartSpan:
387
- return cls(start=position.getStart(), end=position.getLimit())
388
-
389
- def __contains__(self, inner: _PartSpan) -> bool:
390
- return inner.start >= self.start and inner.end <= self.end
391
-
392
-
393
390
  class DateTimeFormat:
394
391
  locale: Locale
395
392
  options: DateTimeFormatOptions
@@ -410,9 +407,13 @@ class DateTimeFormat:
410
407
  else:
411
408
  self.options = DateTimeFormatOptions(**options)
412
409
 
410
+ @cached_property
411
+ def _icu_datetime_pattern_generator(self) -> icu.DateTimePatternGenerator:
412
+ return icu.DateTimePatternGenerator.createInstance(self.locale._icu_locale)
413
+
413
414
  @cached_property
414
415
  def _matched_pattern(self) -> _MatchedFormatPattern:
415
- return _options_to_format_pattern(self.locale._icu_locale, self.options)
416
+ return _options_to_format_pattern(self._icu_datetime_pattern_generator, self.options)
416
417
 
417
418
  @cached_property
418
419
  def _icu_pattern(self) -> str:
@@ -425,7 +426,12 @@ class DateTimeFormat:
425
426
  def format(self, datetime_: dt.datetime, /) -> str:
426
427
  return self._icu_date_format.format(datetime_)
427
428
 
428
- def format_to_parts(self, datetime_: dt.datetime, /) -> Iterable[DateTimePatternPart]:
429
+ def format_to_parts(self, datetime_: dt.datetime, /) -> Iterable[DateTimeFormattedPart]:
430
+ # Sadly there is no formatToValue() function available inside the SimpleDateFormat class
431
+ # ICU provides (formatToValue() could return a "formatted" object one could iterate
432
+ # over to get the different parts). This means we need to parse the pattern ourselved here
433
+ # and create the parts ourselves. Luckily we can adapt the ICU code for parsing the pattern
434
+ # easily and thus still have a relatively sane implementation.
429
435
  # Based on https://github.com/unicode-org/icu/blob/6fb634d81d10dd4667fb3fbcd1f19d9b9b926e62/icu4c/source/i18n/smpdtfmt.cpp#L1060
430
436
  pattern = self._icu_pattern
431
437
  in_quote = False
@@ -438,7 +444,7 @@ class DateTimeFormat:
438
444
  char = pattern[i]
439
445
 
440
446
  if char != prev_char and count > 0:
441
- yield DateTimePatternPart(
447
+ yield DateTimeFormattedPart(
442
448
  type=_PATTERN_SYMBOL_TO_TYPE.get(prev_char, "unknown"),
443
449
  value=icu.SimpleDateFormat(prev_char * count, self.locale._icu_locale).format(datetime_),
444
450
  _pattern=prev_char * count,
@@ -453,7 +459,7 @@ class DateTimeFormat:
453
459
  in_quote = not in_quote
454
460
  elif not in_quote and char in _PATTERN_SYMBOLS:
455
461
  if literal_chars:
456
- yield DateTimePatternPart(
462
+ yield DateTimeFormattedPart(
457
463
  type="literal",
458
464
  value="".join(literal_chars),
459
465
  )
@@ -466,21 +472,23 @@ class DateTimeFormat:
466
472
  i += 1
467
473
 
468
474
  if count > 0:
469
- yield DateTimePatternPart(
475
+ yield DateTimeFormattedPart(
470
476
  type=_PATTERN_SYMBOL_TO_TYPE.get(prev_char, "unknown"),
471
477
  value=icu.SimpleDateFormat(prev_char * count, self.locale._icu_locale).format(datetime_),
472
478
  _pattern=prev_char * count,
473
479
  )
474
480
  assert not literal_chars # noqa: S101
475
481
  elif literal_chars:
476
- yield DateTimePatternPart(
482
+ yield DateTimeFormattedPart(
477
483
  type="literal",
478
484
  value="".join(literal_chars),
479
485
  )
480
486
 
481
487
  @cached_property
482
488
  def _icu_dateinterval_format(self) -> icu.DateIntervalFormat:
483
- possible_skeletons = list(_options_to_possible_skeletons(self.options))
489
+ possible_skeletons = list(
490
+ _options_to_possible_skeletons(self._icu_datetime_pattern_generator, self.options),
491
+ )
484
492
  return icu.DateIntervalFormat.createInstance(possible_skeletons[0], self.locale._icu_locale)
485
493
 
486
494
  def format_range(
@@ -495,22 +503,22 @@ class DateTimeFormat:
495
503
  self,
496
504
  start_datetime: dt.datetime,
497
505
  end_datetime: dt.datetime,
498
- ) -> Iterable[DateTimeIntervalPatternPart]:
506
+ ) -> Iterable[DateTimeIntervalFormattedPart]:
499
507
  icu_date_interval = icu.DateInterval(start_datetime, end_datetime)
500
508
  formatted = self._icu_dateinterval_format.formatToValue(icu_date_interval)
501
509
 
502
510
  # Find spans of both datetimes (used to determine which parts have which source)
503
- span_start = _PartSpan.empty()
504
- span_end = _PartSpan.empty()
511
+ span_start = _FormattedPartSpan.empty()
512
+ span_end = _FormattedPartSpan.empty()
505
513
  for part in formatted:
506
514
  if part.getCategory() == icu.UFieldCategory.DATE_INTERVAL_SPAN:
507
515
  match part.getField():
508
516
  case 0:
509
- span_start = _PartSpan.from_constrained_fieldposition(part)
517
+ span_start = _FormattedPartSpan.from_constrained_fieldposition(part)
510
518
  case 1:
511
- span_end = _PartSpan.from_constrained_fieldposition(part)
519
+ span_end = _FormattedPartSpan.from_constrained_fieldposition(part)
512
520
 
513
- def source_of(span: _PartSpan) -> Literal["start_range", "end_range", "shared"]:
521
+ def source_of(span: _FormattedPartSpan) -> Literal["start_range", "end_range", "shared"]:
514
522
  if span in span_start:
515
523
  return "start_range"
516
524
  elif span in span_end:
@@ -522,16 +530,16 @@ class DateTimeFormat:
522
530
  result_string = str(formatted)
523
531
  last_end = 0
524
532
  for part in formatted:
525
- span = _PartSpan.from_constrained_fieldposition(part)
533
+ span = _FormattedPartSpan.from_constrained_fieldposition(part)
526
534
  if span.start > last_end:
527
- yield DateTimeIntervalPatternPart(
535
+ yield DateTimeIntervalFormattedPart(
528
536
  type="literal",
529
537
  value=result_string[last_end:span.start],
530
- source=source_of(_PartSpan(start=last_end, end=span.start)),
538
+ source=source_of(_FormattedPartSpan(start=last_end, end=span.start)),
531
539
  )
532
540
 
533
541
  if part.getCategory() == icu.UFieldCategory.DATE:
534
- yield DateTimeIntervalPatternPart(
542
+ yield DateTimeIntervalFormattedPart(
535
543
  type=_PATTERN_FIELD_TO_TYPE.get(part.getField(), "unknown"),
536
544
  value=result_string[span.start:span.end],
537
545
  source=source_of(span),
@@ -541,8 +549,8 @@ class DateTimeFormat:
541
549
 
542
550
  # Ensure we didn't miss anything at the end
543
551
  if last_end < len(result_string):
544
- yield DateTimeIntervalPatternPart(
552
+ yield DateTimeIntervalFormattedPart(
545
553
  type="literal",
546
554
  value=result_string[last_end:],
547
- source=source_of(_PartSpan(start=last_end, end=len(result_string))),
555
+ source=source_of(_FormattedPartSpan(start=last_end, end=len(result_string))),
548
556
  )
@@ -7,10 +7,12 @@ from typing import TYPE_CHECKING
7
7
 
8
8
  import icu
9
9
 
10
+ from ._utils import _FormattedPartSpan
10
11
  from .locale import Locale
11
12
 
12
13
  if TYPE_CHECKING:
13
- from typing import NotRequired, TypedDict
14
+ from collections.abc import Iterable
15
+ from typing import Literal, NotRequired, TypedDict
14
16
 
15
17
  from ._types import (
16
18
  CurrencyDisplayT,
@@ -23,6 +25,14 @@ if TYPE_CHECKING:
23
25
  )
24
26
 
25
27
  type NumberT = decimal.Decimal | float | int
28
+ type NumberFormattedPartTypeT = Literal[
29
+ "literal", "unknown",
30
+ "integer", "group", "decimal", "fraction", "compact",
31
+ "exponent_separator", "exponent_minus_sign", "exponent_integer",
32
+ "nan", "infinity",
33
+ "plus_sign", "minus_sign", "percent_sign",
34
+ "unit", "currency",
35
+ ]
26
36
 
27
37
  # Important: Must be the same as DateTimeFormatOptions
28
38
  # (nothing is required, as this will be used to construct a
@@ -43,6 +53,41 @@ if TYPE_CHECKING:
43
53
  _CURRENCY_DISPLAY_TO_JSON_MAP: dict[str, str] = {
44
54
  "narrow_symbol": "narrowSymbol",
45
55
  }
56
+ _FORMATTED_FIELD_TO_TYPE: dict[icu.UNumberFormatFields, NumberFormattedPartTypeT] = {
57
+ icu.UNumberFormatFields.INTEGER: "integer",
58
+ icu.UNumberFormatFields.GROUPING_SEPARATOR: "group",
59
+ icu.UNumberFormatFields.DECIMAL_SEPARATOR: "decimal",
60
+ icu.UNumberFormatFields.FRACTION: "fraction",
61
+ icu.UNumberFormatFields.COMPACT: "compact",
62
+ icu.UNumberFormatFields.EXPONENT_SYMBOL: "exponent_separator",
63
+ icu.UNumberFormatFields.EXPONENT_SIGN: "exponent_minus_sign",
64
+ icu.UNumberFormatFields.EXPONENT: "exponent_integer",
65
+ # TODO(ddanier): How to do these?
66
+ # https://github.com/ddanier/python-intl/issues/5
67
+ # icu.UNumberFormatFields.HOW??: "nan",
68
+ # icu.UNumberFormatFields.HOW??: "infinity",
69
+ # icu.UNumberFormatFields.HOW??: "plus_sign",
70
+ icu.UNumberFormatFields.SIGN: "minus_sign",
71
+ icu.UNumberFormatFields.PERCENT: "unit",
72
+ icu.UNumberFormatFields.MEASURE_UNIT: "unit",
73
+ icu.UNumberFormatFields.CURRENCY: "currency",
74
+ }
75
+ _FORMATTED_FIELD_TO_TYPE_OVERRIDES_BY_STYLE: dict[
76
+ StyleT,
77
+ dict[icu.UNumberFormatFields, NumberFormattedPartTypeT],
78
+ ] = {
79
+ "percent": {
80
+ icu.UNumberFormatFields.PERCENT: "percent_sign",
81
+ },
82
+ }
83
+ _COMPONENT_TO_JSON_MAP = {
84
+ "exponent_separator": "exponentSeparator",
85
+ "exponent_minus_sign": "exponentMinusSign",
86
+ "exponent_integer": "exponentInteger",
87
+ "plus_sign": "plusSign",
88
+ "minus_sign": "minusSign",
89
+ "percent_sign": "percentSign",
90
+ }
46
91
 
47
92
 
48
93
  class InvalidNumberFormatOptionError(ValueError):
@@ -94,12 +139,25 @@ class NumberFormatOptions:
94
139
  }
95
140
 
96
141
 
142
+ @dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
143
+ class NumberFormattedPart:
144
+ type: NumberFormattedPartTypeT
145
+ value: str
146
+
147
+ def to_json(self) -> dict[str, str]:
148
+ return {
149
+ "type": _COMPONENT_TO_JSON_MAP.get(self.type, self.type),
150
+ "value": self.value,
151
+ }
152
+
153
+
97
154
  def _options_to_skeleton(options: NumberFormatOptions) -> str:
98
155
  skeleton_parts: list[str] = []
99
156
 
100
157
  match options.style:
101
158
  case "decimal":
102
159
  skeleton_parts.append("decimal-auto")
160
+ skeleton_parts.append(".###")
103
161
  case "percent":
104
162
  skeleton_parts.append("precision-integer")
105
163
  skeleton_parts.append("scale/100")
@@ -120,6 +178,7 @@ def _options_to_skeleton(options: NumberFormatOptions) -> str:
120
178
  skeleton_parts.append("unit-width-full-name")
121
179
  case "unit":
122
180
  skeleton_parts.append(f"unit/{options.unit}")
181
+ skeleton_parts.append(".###")
123
182
  match options.unit_display:
124
183
  case "short":
125
184
  skeleton_parts.append("unit-width-short")
@@ -165,6 +224,94 @@ class NumberFormat:
165
224
  case decimal.Decimal():
166
225
  return self._icu_number_formatter.formatDecimal(str(value).encode("ascii"))
167
226
 
227
+ def format_to_parts(self, value: NumberT, /) -> Iterable[NumberFormattedPart]:
228
+ match value:
229
+ case int():
230
+ formatted = self._icu_number_formatter.formatIntToValue(value)
231
+ case float():
232
+ formatted = self._icu_number_formatter.formatDoubleToValue(value)
233
+ case decimal.Decimal():
234
+ formatted = self._icu_number_formatter.formatDecimalToValue(str(value).encode("ascii"))
235
+
236
+ # Break result string into parts
237
+ result_string = str(formatted)
238
+
239
+ last_end = 0
240
+ parts = list(formatted)
241
+
242
+ # Parts are not in subsequent order, the lost might be something like for "123,456" ("," is the group):
243
+ # * "integer" from char 0 to 7
244
+ # * "group" from char 3 to 4
245
+ # ...this means we need to find the next most suitable group based on the current position in the
246
+ # formatted string and the available parts.
247
+ def _next_parts() -> tuple[icu.ConstrainedFieldPosition, icu.ConstrainedFieldPosition | None] | None:
248
+ next_parts = sorted(
249
+ (
250
+ part for part in parts
251
+ if (
252
+ # Parts that follow the last part...
253
+ part.getStart() >= last_end
254
+ # ...or parts we already had, but didn't end yet
255
+ or (part.getStart() < last_end and part.getLimit() > last_end)
256
+ )
257
+ ),
258
+ key=lambda part: (
259
+ # Always prefer parts starting at the current position
260
+ 0 if part.getStart() == last_end else 1,
261
+ # Then prefer the ones starting next to the current position, shorter ones preferred
262
+ part.getStart(),
263
+ part.getLimit(),
264
+ ),
265
+ )
266
+ if not next_parts:
267
+ return None
268
+
269
+ return (
270
+ next_parts[0],
271
+ next_parts[1] if len(next_parts) > 1 else None,
272
+ )
273
+
274
+ while (next_parts := _next_parts()):
275
+ part, subsequent_part = next_parts
276
+
277
+ span = _FormattedPartSpan(
278
+ # start cannot move to a previous position
279
+ start=max(part.getStart(), last_end),
280
+ # end is either the normal end of the span or it might be the start of a susequent
281
+ # part of both overlap
282
+ end=(
283
+ min(part.getLimit(), subsequent_part.getStart())
284
+ if subsequent_part and subsequent_part.getStart() > last_end
285
+ else part.getLimit()
286
+ ),
287
+ )
288
+ if span.start > last_end:
289
+ yield NumberFormattedPart(
290
+ type="literal",
291
+ value=result_string[last_end:span.start],
292
+ )
293
+
294
+ if part.getCategory() == icu.UFieldCategory.NUMBER:
295
+ type_= _FORMATTED_FIELD_TO_TYPE.get(part.getField(), "unknown")
296
+ if (
297
+ self.options.style in _FORMATTED_FIELD_TO_TYPE_OVERRIDES_BY_STYLE
298
+ and part.getField() in _FORMATTED_FIELD_TO_TYPE_OVERRIDES_BY_STYLE[self.options.style]
299
+ ):
300
+ type_ = _FORMATTED_FIELD_TO_TYPE_OVERRIDES_BY_STYLE[self.options.style][part.getField()]
301
+ yield NumberFormattedPart(
302
+ type=type_,
303
+ value=result_string[span.start:span.end],
304
+ )
305
+
306
+ last_end = span.end
307
+
308
+ # Ensure we didn't miss anything at the end
309
+ if last_end < len(result_string):
310
+ yield NumberFormattedPart(
311
+ type="literal",
312
+ value=result_string[last_end:],
313
+ )
314
+
168
315
  @cached_property
169
316
  def _icu_number_range_formatter(self) -> icu.LocalizedNumberRangeFormatter:
170
317
  skeleton = _options_to_skeleton(self.options)
File without changes