python-intl 0.8.0__tar.gz → 0.10.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.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.
@@ -49,7 +49,7 @@ Intl.DateTimeFormatOptions(time_zone_name="short_offset").to_json()
49
49
  import datetime as dt
50
50
  import python_intl as Intl
51
51
 
52
- locale = Intl.DateTimeFormat("de-DE")
52
+ locale = Intl.Locale("de-DE")
53
53
  ```
54
54
 
55
55
  #### Compatibility
@@ -58,6 +58,38 @@ locale = Intl.DateTimeFormat("de-DE")
58
58
  allow using the locale class instead of a string with the other classes. There will
59
59
  be more later.
60
60
 
61
+ ### `Intl.NumberFormat`
62
+
63
+ #### Example usage
64
+
65
+ ```python
66
+ import python_intl as Intl
67
+
68
+ # Format liters
69
+ number = 1234.567
70
+ formatter = Intl.NumberFormat("de-DE", {"style": "unit", "unit": "liter"})
71
+ formatter.format(number)
72
+ # Result = "1.234,567 l"
73
+
74
+ # Format euros
75
+ number = 1234.567
76
+ formatter = Intl.NumberFormat("de-DE", {"style": "currency", "currency": "EUR"})
77
+ formatter.format(number)
78
+ # Result = "1.234,57 €"
79
+ # Note: Result will be automatically rounded to two decimal places, as EUR defines.
80
+ ```
81
+
82
+ #### Compatibility
83
+
84
+ | Method | Status | Python name |
85
+ | --------------------------------- | :----: | ------------------------------------ |
86
+ | `NumberFormat.format` | ✅ | |
87
+ | `NumberFormat.formatToParts` | ❌ | `NumberFormat.format_to_parts` |
88
+ | `NumberFormat.supportedLocalesOf` | ❌ | |
89
+ | `NumberFormat.formatRange` | ✅ | `NumberFormat.format_range` |
90
+ | `NumberFormat.formatRangeToParts` | ❌ | `NumberFormat.format_range_to_parts` |
91
+ | `NumberFormat.resolvedOptions` | ❌ | |
92
+
61
93
  ### `Intl.DateTimeFormat`
62
94
 
63
95
  #### Example usage
@@ -125,7 +157,8 @@ Be sure to be able to install `PyICU`, see the installation docs there:
125
157
  https://gitlab.pyicu.org/main/pyicu#installing-pyicu
126
158
 
127
159
  **Hint:** I mainly did run into issues with `pkg-config` not finding the ICU library,
128
- setting `PKG_CONFIG_PATH` accordingly helps most of the time I guess.
160
+ setting `PKG_CONFIG_PATH` accordingly helps most of the time I guess. See [`.envrc`](.envrc)
161
+ for how to set this up correctly on `nix` based systems.
129
162
 
130
163
  When this is done you should be able to install `python-intl` using any package
131
164
  manager, like `pip install python-intl` or `uv add python-intl`.
@@ -138,4 +171,5 @@ are unsure about whether your changes really suits the project please create an
138
171
  issue first, to talk about this.
139
172
 
140
173
  Please do not contribute AI generated code unless we explicitly talked about
141
- 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.8.0"
3
+ version = "0.10.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"
@@ -17,11 +17,15 @@ Repository = "https://github.com/ddanier/python-intl"
17
17
 
18
18
  [dependency-groups]
19
19
  dev = [
20
+ "basedpyright>=1.40.1",
20
21
  "mypy>=2.3.1",
22
+ "packaging>=26.3",
23
+ "pylsp-mypy>=0.8.0",
21
24
  "pyright>=1.1.411",
22
25
  "pytest>=9.1.1",
23
26
  "pytest-cov>=7.1.0",
24
27
  "pytest-xdist>=3.8.0",
28
+ "python-lsp-server>=1.15.0",
25
29
  "ruff>=0.16.3",
26
30
  "tox>=4.60.0",
27
31
  "ty>=0.0.72",
@@ -39,62 +43,88 @@ output-format = "grouped"
39
43
 
40
44
  [tool.ruff.lint]
41
45
  select = [
42
- "F",
46
+ "A",
47
+ "ANN",
48
+ "ARG",
49
+ "ASYNC",
50
+ "B",
51
+ "BLE",
52
+ "C4",
53
+ "COM",
54
+ "DTZ",
43
55
  "E",
44
- "W",
45
- "C",
56
+ "EM",
57
+ "EXE",
58
+ "F",
59
+ "FA",
60
+ "FBT",
61
+ "FURB",
46
62
  "I",
63
+ "ICN",
64
+ "ISC",
47
65
  "N",
48
- "UP",
49
- "ANN",
66
+ "PERF",
67
+ "PIE",
68
+ "PL",
69
+ "PT",
70
+ "PTH",
71
+ "Q",
72
+ "RSE",
73
+ "RUF",
50
74
  "S",
51
- "B",
52
- "A",
53
- "COM",
54
- "C4",
75
+ "SIM",
76
+ "SLOT",
77
+ "T10",
55
78
  "T20",
56
- "PT",
57
- "ARG",
79
+ "TC",
58
80
  "TD",
59
- "RUF",
60
- ]
61
- ignore = [
62
- "A001",
63
- "A002",
64
- "A003",
65
- "ANN401",
66
- "C901",
67
- "N8",
68
- "B008",
69
- "F405",
70
- "F821",
71
- "TD003",
81
+ "TID",
82
+ "TRY",
83
+ "UP",
84
+ "W",
72
85
  ]
86
+ ignore = ["N812"]
73
87
 
74
88
  [tool.ruff.lint.per-file-ignores]
75
- "__init__.py" = ["F401"]
76
- "conftest.py" = [
89
+ "test_*.py" = [
77
90
  "S101",
78
- "ANN",
79
- "F401",
91
+ "ANN201",
80
92
  ]
81
- "test_*.py" = [
93
+ "conftest.py" = [
82
94
  "S101",
83
- "ANN",
84
- "F401",
95
+ "ANN201",
85
96
  ]
86
97
 
87
98
  [tool.ruff.lint.isort]
88
99
  combine-as-imports = true
89
100
  force-wrap-aliases = true
90
101
 
91
- [tool.pyright]
102
+ [tool.ty.analysis]
103
+ replace-imports-with-any = ["icu.**"]
104
+
105
+ [[tool.mypy.overrides]]
106
+ module = ["icu.*"]
107
+ ignore_missing_imports = true
108
+
109
+ [tool.basedpyright]
92
110
  pythonVersion = "3.12"
111
+ reportAny = false
112
+ reportExplicitAny = false
113
+ reportUnusedCallResult = false
114
+ reportMatchNotExhaustive = false
115
+ reportUnknownLambdaType = false
116
+ reportPrivateUsage = false
117
+ allowedUntypedLibraries = ["icu"]
118
+ reportAttributeAccessIssue = false
119
+ reportUnknownVariableType = false
120
+ reportUnknownMemberType = false
121
+ reportUnknownParameterType = false
122
+ reportUnknownArgumentType = false
93
123
 
94
124
  [tool.uv.build-backend]
95
125
  module-name = "python_intl"
96
126
  module-root = ""
97
127
 
98
128
  [build-system]
99
- requires = ["uv_build>=0.12.3,<0.13.0"]
129
+ requires = ["uv_build>=0.12.3,<0.14.0"]
100
130
  build-backend = "uv_build"
@@ -0,0 +1,134 @@
1
+ [project]
2
+ name = "python-intl"
3
+ version = "0.10.0"
4
+ description = "Python implementation of the Intl JavaScript API"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "David Danier", email = "david.danier@gmail.com" }
8
+ ]
9
+ license = "MIT"
10
+ license-files = ["LICENSE"]
11
+ requires-python = ">=3.12"
12
+ dependencies = [
13
+ "pyicu>=2.17.0",
14
+ ]
15
+
16
+ [project.urls]
17
+ Repository = "https://github.com/ddanier/python-intl"
18
+
19
+ [dependency-groups]
20
+ dev = [
21
+ "basedpyright>=1.40.1",
22
+ "mypy>=2.3.1",
23
+ "packaging>=26.3",
24
+ "pylsp-mypy>=0.8.0",
25
+ "pyright>=1.1.411",
26
+ "pytest>=9.1.1",
27
+ "pytest-cov>=7.1.0",
28
+ "pytest-xdist>=3.8.0",
29
+ "python-lsp-server>=1.15.0",
30
+ "ruff>=0.16.3",
31
+ "tox>=4.60.0",
32
+ "ty>=0.0.72",
33
+ ]
34
+
35
+ [tool.pytest.ini_options]
36
+ markers = [
37
+ "unit: mark a test as a unit test",
38
+ "node: mark tests jun against the node/JS implementation",
39
+ ]
40
+
41
+ [tool.ruff]
42
+ line-length = 115
43
+ output-format = "grouped"
44
+
45
+ [tool.ruff.lint]
46
+ select = [
47
+ "A", # flake8-builtins
48
+ "ANN", # flake8-annotations
49
+ "ARG", # flake8-unused-arguments
50
+ "ASYNC", # flake8-async
51
+ "B", # flake8-bugbear
52
+ "BLE", # flake8-blind-except
53
+ "C4", # flake8-comprehensions
54
+ "COM", # flake8-commas
55
+ "DTZ", # flake8-datetimez
56
+ "E", # pycodestyle errors
57
+ "EM", # flake8-errmsg
58
+ "EXE", # flake8-executable
59
+ "F", # pyflakes
60
+ "FA", # flake8-future-annotations
61
+ "FBT", # flake8-boolean-trap
62
+ "FURB", # refurb
63
+ "I", # isort
64
+ "ICN", # flake8-import-conventions
65
+ "ISC", # flake8-implicit-str-concat
66
+ "N", # pep8-naming
67
+ "PERF", # perflint
68
+ "PIE", # flake8-pie
69
+ "PL", # pylint
70
+ "PT", # flake8-pytest-style
71
+ "PTH", # flake8-use-pathlib
72
+ "Q", # flake8-quotes
73
+ "RSE", # flake8-raise
74
+ "RUF", # ruff-specific rules
75
+ "S", # flake8-bandit
76
+ "SIM", # flake8-simplify
77
+ "SLOT", # flake8-slots
78
+ "T10", # flake8-debugger
79
+ "T20", # flake8-print
80
+ "TC", # flake8-type-checking
81
+ "TD", # flake8-todos
82
+ "TID", # flake8-tidy-imports
83
+ "TRY", # tryceratops
84
+ "UP", # pyupgrade
85
+ "W", # pycodestyle warnings
86
+ ]
87
+ ignore = [
88
+ "N812", # Allow using "import python_intl as Intl"
89
+ ]
90
+
91
+ [tool.ruff.lint.per-file-ignores]
92
+ "test_*.py" = [
93
+ "S101", # Allow usage of assert in tests
94
+ "ANN201", # Don't require to define return types in tests
95
+ ]
96
+ "conftest.py" = [
97
+ "S101", # Allow usage of assert in tests
98
+ "ANN201", # Don't require to define return types in tests
99
+ ]
100
+
101
+ [tool.ruff.lint.isort]
102
+ combine-as-imports = true
103
+ force-wrap-aliases = true
104
+
105
+ [tool.ty.analysis]
106
+ replace-imports-with-any = ["icu.**"]
107
+
108
+ [[tool.mypy.overrides]]
109
+ module = ["icu.*"]
110
+ ignore_missing_imports = true
111
+
112
+ [tool.basedpyright]
113
+ pythonVersion = "3.12"
114
+ reportAny = false
115
+ reportExplicitAny = false
116
+ reportUnusedCallResult = false
117
+ reportMatchNotExhaustive = false
118
+ reportUnknownLambdaType = false
119
+ reportPrivateUsage = false
120
+ # The following are only necessary cause of untyped icu library
121
+ allowedUntypedLibraries = ["icu"]
122
+ reportAttributeAccessIssue = false
123
+ reportUnknownVariableType = false
124
+ reportUnknownMemberType = false
125
+ reportUnknownParameterType = false
126
+ reportUnknownArgumentType = false
127
+
128
+ [build-system]
129
+ requires = ["uv_build>=0.12.3,<0.14.0"]
130
+ build-backend = "uv_build"
131
+
132
+ [tool.uv.build-backend]
133
+ module-name = "python_intl"
134
+ module-root = ""
@@ -0,0 +1,16 @@
1
+ from .collator import (
2
+ Collator as Collator,
3
+ CollatorOptions as CollatorOptions,
4
+ )
5
+ from .datetimeformat import (
6
+ DateTimeFormat as DateTimeFormat,
7
+ DateTimeFormatOptions as DateTimeFormatOptions,
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,
16
+ )
@@ -0,0 +1,94 @@
1
+ from typing import TYPE_CHECKING
2
+
3
+ if TYPE_CHECKING:
4
+ from typing import Literal
5
+
6
+ type LocaleMatcherT = Literal["best fit", "lookup"]
7
+ type Hour12T = bool
8
+ type HourCycleT = Literal["h11", "h12", "h23", "h24"]
9
+
10
+ # datetime
11
+ type EraFormatT = Literal["long", "short", "narrow"]
12
+ type YearFormatT = Literal["numeric", "2-digit"]
13
+ type MonthFormatT = Literal["numeric", "2-digit", "long", "short", "narrow"]
14
+ type WeekdayFormatT = Literal["long", "short", "narrow"]
15
+ type DayFormatT = Literal["numeric", "2-digit"]
16
+ type DayPeriodFormatT = Literal["long", "short", "narrow"]
17
+ type HourFormatT = Literal["numeric", "2-digit"]
18
+ type MinuteFormatT = Literal["numeric", "2-digit"]
19
+ type SecondFormatT = Literal["numeric", "2-digit"]
20
+ type FractionSecondDigitsFormatT = Literal[1, 2, 3]
21
+ type TimezoneNameFormatT = Literal[
22
+ "short",
23
+ "long",
24
+ "short_offset",
25
+ "long_offset",
26
+ "short_generic",
27
+ "long_generic",
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
89
+ # type UsageT = Literal["sort", "search"]
90
+ # type CollationT = Literal["emoji", "pinyin", "stroke"]
91
+ type CaseFirstT = Literal["upper", "lower", "false"]
92
+ type SensitivityT = Literal["base", "accent", "case", "variant"]
93
+
94
+ type ComparisonResultT = Literal[-1, 0, 1]
@@ -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))),
@@ -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,63 +0,0 @@
1
- [project]
2
- name = "python-intl"
3
- version = "0.8.0"
4
- description = "Python implementation of the Intl JavaScript API"
5
- readme = "README.md"
6
- authors = [
7
- { name = "David Danier", email = "david.danier@gmail.com" }
8
- ]
9
- license = "MIT"
10
- license-files = ["LICENSE"]
11
- requires-python = ">=3.12"
12
- dependencies = [
13
- "pyicu>=2.16.2",
14
- ]
15
-
16
- [project.urls]
17
- Repository = "https://github.com/ddanier/python-intl"
18
-
19
- [dependency-groups]
20
- dev = [
21
- "mypy>=2.3.1",
22
- "pyright>=1.1.411",
23
- "pytest>=9.1.1",
24
- "pytest-cov>=7.1.0",
25
- "pytest-xdist>=3.8.0",
26
- "ruff>=0.16.3",
27
- "tox>=4.60.0",
28
- "ty>=0.0.72",
29
- ]
30
-
31
- [tool.pytest.ini_options]
32
- markers = [
33
- "unit: mark a test as a unit test",
34
- "node: mark tests jun against the node/JS implementation",
35
- ]
36
-
37
- [tool.ruff]
38
- line-length = 115
39
- output-format = "grouped"
40
-
41
- [tool.ruff.lint]
42
- select = ["F","E","W","C","I","N","UP","ANN","S","B","A","COM","C4","T20","PT","ARG","TD","RUF"]
43
- ignore = ["A001","A002","A003","ANN401","C901","N8","B008","F405","F821","TD003"]
44
-
45
- [tool.ruff.lint.per-file-ignores]
46
- "__init__.py" = ["F401"]
47
- "conftest.py" = ["S101","ANN","F401"]
48
- "test_*.py" = ["S101","ANN","F401"]
49
-
50
- [tool.ruff.lint.isort]
51
- combine-as-imports = true
52
- force-wrap-aliases = true
53
-
54
- [tool.pyright]
55
- pythonVersion = "3.12"
56
-
57
- [build-system]
58
- requires = ["uv_build>=0.12.3,<0.13.0"]
59
- build-backend = "uv_build"
60
-
61
- [tool.uv.build-backend]
62
- module-name = "python_intl"
63
- module-root = ""
@@ -1,11 +0,0 @@
1
- from .collator import (
2
- Collator as Collator,
3
- CollatorOptions as CollatorOptions,
4
- )
5
- from .datetimeformat import (
6
- DateTimeFormat as DateTimeFormat,
7
- DateTimeFormatOptions as DateTimeFormatOptions,
8
- DateTimeIntervalPatternPart as DateTimeIntervalPatternPart,
9
- DateTimePatternPart as DateTimePatternPart,
10
- FormatPatternNotFoundException as FormatPatternNotFoundException,
11
- )
@@ -1,34 +0,0 @@
1
- from typing import TYPE_CHECKING
2
-
3
- if TYPE_CHECKING:
4
- from typing import Literal
5
-
6
- type LocaleMatcherT = Literal["best fit", "lookup"]
7
- type Hour12T = bool
8
- type HourCycleT = Literal["h11", "h12", "h23", "h24"]
9
-
10
- type EraFormatT = Literal["long", "short", "narrow"]
11
- type YearFormatT = Literal["numeric", "2-digit"]
12
- type MonthFormatT = Literal["numeric", "2-digit", "long", "short", "narrow"]
13
- type WeekdayFormatT = Literal["long", "short", "narrow"]
14
- type DayFormatT = Literal["numeric", "2-digit"]
15
- type DayPeriodFormatT = Literal["long", "short", "narrow"]
16
- type HourFormatT = Literal["numeric", "2-digit"]
17
- type MinuteFormatT = Literal["numeric", "2-digit"]
18
- type SecondFormatT = Literal["numeric", "2-digit"]
19
- type FractionSecondDigitsFormatT = Literal[1, 2, 3]
20
- type TimezoneNameFormatT = Literal[
21
- "short",
22
- "long",
23
- "short_offset",
24
- "long_offset",
25
- "short_generic",
26
- "long_generic",
27
- ]
28
-
29
- # type UsageT = Literal["sort", "search"]
30
- # type CollationT = Literal["emoji", "pinyin", "stroke"]
31
- type CaseFirstT = Literal["upper", "lower", "false"]
32
- type SensitivityT = Literal["base", "accent", "case", "variant"]
33
-
34
- type ComparisonResultT = Literal[-1, 0, 1]
File without changes