python-intl 0.10.0__tar.gz → 0.11.1__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,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-intl
3
- Version: 0.10.0
3
+ Version: 0.11.1
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>
@@ -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` |
@@ -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` |
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "python-intl"
3
- version = "0.10.0"
3
+ version = "0.11.1"
4
4
  description = "Python implementation of the Intl JavaScript API"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "python-intl"
3
- version = "0.10.0"
3
+ version = "0.11.1"
4
4
  description = "Python implementation of the Intl JavaScript API"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -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
@@ -6,6 +6,7 @@ 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:
@@ -386,23 +387,6 @@ def _options_to_format_pattern(
386
387
  raise FormatPatternNotFoundError(error)
387
388
 
388
389
 
389
- @dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
390
- class _PartSpan:
391
- start: int
392
- end: int
393
-
394
- @classmethod
395
- def empty(cls) -> _PartSpan:
396
- return cls(start=0, end=0)
397
-
398
- @classmethod
399
- def from_constrained_fieldposition(cls, position: icu.ConstrainedFieldPosition) -> _PartSpan:
400
- return cls(start=position.getStart(), end=position.getLimit())
401
-
402
- def __contains__(self, inner: _PartSpan) -> bool:
403
- return inner.start >= self.start and inner.end <= self.end
404
-
405
-
406
390
  class DateTimeFormat:
407
391
  locale: Locale
408
392
  options: DateTimeFormatOptions
@@ -524,17 +508,17 @@ class DateTimeFormat:
524
508
  formatted = self._icu_dateinterval_format.formatToValue(icu_date_interval)
525
509
 
526
510
  # Find spans of both datetimes (used to determine which parts have which source)
527
- span_start = _PartSpan.empty()
528
- span_end = _PartSpan.empty()
511
+ span_start = _FormattedPartSpan.empty()
512
+ span_end = _FormattedPartSpan.empty()
529
513
  for part in formatted:
530
514
  if part.getCategory() == icu.UFieldCategory.DATE_INTERVAL_SPAN:
531
515
  match part.getField():
532
516
  case 0:
533
- span_start = _PartSpan.from_constrained_fieldposition(part)
517
+ span_start = _FormattedPartSpan.from_constrained_fieldposition(part)
534
518
  case 1:
535
- span_end = _PartSpan.from_constrained_fieldposition(part)
519
+ span_end = _FormattedPartSpan.from_constrained_fieldposition(part)
536
520
 
537
- def source_of(span: _PartSpan) -> Literal["start_range", "end_range", "shared"]:
521
+ def source_of(span: _FormattedPartSpan) -> Literal["start_range", "end_range", "shared"]:
538
522
  if span in span_start:
539
523
  return "start_range"
540
524
  elif span in span_end:
@@ -546,12 +530,12 @@ class DateTimeFormat:
546
530
  result_string = str(formatted)
547
531
  last_end = 0
548
532
  for part in formatted:
549
- span = _PartSpan.from_constrained_fieldposition(part)
533
+ span = _FormattedPartSpan.from_constrained_fieldposition(part)
550
534
  if span.start > last_end:
551
535
  yield DateTimeIntervalFormattedPart(
552
536
  type="literal",
553
537
  value=result_string[last_end:span.start],
554
- source=source_of(_PartSpan(start=last_end, end=span.start)),
538
+ source=source_of(_FormattedPartSpan(start=last_end, end=span.start)),
555
539
  )
556
540
 
557
541
  if part.getCategory() == icu.UFieldCategory.DATE:
@@ -568,5 +552,5 @@ class DateTimeFormat:
568
552
  yield DateTimeIntervalFormattedPart(
569
553
  type="literal",
570
554
  value=result_string[last_end:],
571
- source=source_of(_PartSpan(start=last_end, end=len(result_string))),
555
+ source=source_of(_FormattedPartSpan(start=last_end, end=len(result_string))),
572
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
File without changes