Handle negative and float values in pluralize method

This commit is contained in:
2026-11-21 00:04:52 +01:00
parent 86f3b8a769
commit 1575bec4ac
4 changed files with 126 additions and 37 deletions
+17 -7
View File
@@ -181,14 +181,24 @@ no_count_text = i18n.p("files.found", None)
| Count | Category |
| --- | --- |
| `0` | `zero` |
| `1` | `one` |
| Greater than `1` | `many` |
| `0` (also `0.0` and `-0.0`) | `zero` |
| `1` (also `1.0`) and `-1` | `one` |
| Any other number (`2`, `-2`, `0.5`, `-1.5`, `2.5`, ...) | `many` |
| `None` | `none` |
Negative counts raise `ValueError`. The selected text follows the same current
language, English, `default`, and key fallback order as `t()`. The count is
available to formatting as `{count}`; `#count` is also replaced directly.
The count may be an integer or a float, positive or negative. The category is
chosen from its absolute value, so `-1` selects `one` like `1`. The selected
text follows the same current language, English, `default`, and key fallback
order as `t()`. The count is available to formatting as `{count}`; `#count` is
also replaced directly and inserts the count as Python prints it (for example
`2.5` or `-3`). Use `{count}` with a format specification to control the
number format:
```python
# "many": "{count:.1f} files"
i18n.p("files.found", 2.5) # "2.5 files"
i18n.p("files.found", -2) # "-2.0 files"
```
### Listen for language changes
@@ -239,7 +249,7 @@ it is intended for compatibility and inspection rather than normal lookup.
- `ValueError`: unknown language, invalid JSON, invalid translation structure,
missing or empty `language` metadata, plural entries missing `one` or
`many`, or a negative plural count.
or `many`.
- `FileNotFoundError`: the internal default language folder or its
`strings.json` is unavailable at construction, a selected language has no
usable translation file, or no current/English help file can be found.
+18 -10
View File
@@ -326,14 +326,17 @@ i18n.t("wert", n=42) # formats e.g. "{n:05d}" -> "0004
Translates a pluralized key.
The category is chosen from `count`:
`count` may be an `int` or a `float`, positive or negative. The category is
chosen from its **absolute value**:
| `count` | Category |
| --- | --- |
| `None` | `none` |
| `0` | `zero` |
| `1` | `one` |
| greater than 1 | `many` |
| `0`, `0.0`, `-0.0` | `zero` |
| `1`, `1.0`, `-1` | `one` |
| any other number, e.g. `2`, `-2`, `0.5`, `-1.5`, `2.5` | `many` |
Values such as `NaN` and infinity also select `many`.
Lookup order: active language → English (same category) → `default` → `key`.
A plain string value is also accepted and used for every category, which helps
@@ -342,14 +345,18 @@ with partially converted resources.
In the selected text, `#count` is replaced by the count, and the text is then
formatted with `count` plus any keyword arguments, so `{count}` and extra
placeholders work. A failed formatting returns the text with `#count` already
replaced.
replaced. `#count` inserts the count as Python prints it (`2.5`, `-3`); use a
format specification such as `{count:.1f}` to control the number format.
**Raises** `ValueError` for negative counts (checked before the lookup).
**Raises** `TypeError` if `count` is neither a number nor `None`.
```python
i18n.p("files.found", 0) # "No files found"
i18n.p("files.found", 1) # "One file found"
i18n.p("files.found", -1) # "One file found" (absolute value)
i18n.p("files.found", 5) # "5 files found"
i18n.p("files.found", 2.5) # "2.5 files found"
i18n.p("files.found", -2) # "-2 files found"
i18n.p("files.found", None) # text of the "none" category
i18n.p("files.found", 3, default="{count} things") # used only if the key is unknown
```
@@ -581,7 +588,7 @@ Ki18n("en", local_root=data_dir("my-app"))
| `FileNotFoundError` | `set_language` | The language's files disappeared after start-up. |
| `ValueError` | `set_language` | Unknown language or invalid ID. |
| `ValueError` | `t` | Key refers to a plural object. |
| `ValueError` | `p` | Negative count. |
| `TypeError` | `p` | `count` is neither a number nor `None`. |
| `FileNotFoundError` | `get_help` | No help file for the active language or English. |
After any exception from `set_language`, the previously active language remains
@@ -609,9 +616,10 @@ These points are based on reading the current source code.
`IndexError` and `ValueError` from `str.format`. Placeholders that raise
`AttributeError` or `TypeError` (for example `{name.attr}` or `{name[x]}` with
a string value) propagate to the caller.
- **Fractional counts below 1.** `p()` accepts floats, but values between 0 and 1
(for example `0.5`) match no category and raise `ValueError` with the message
`count must be nonnegative or None`.
- **Simple plural rules.** `p()` knows only the categories `zero`, `one`, `many`
and `none`, chosen from the absolute value of the count. Language-specific
plural rules (for example separate forms for 2–4 in Slavic languages) are not
supported, and fractions such as `1.5` always use `many`.
- **No automatic reload.** Resource files are read when a language is activated;
selecting the already active language does nothing.
- **Plain Markdown help.** `help.md` is returned verbatim; there is no merge with
+13 -10
View File
@@ -434,21 +434,24 @@ class Ki18n:
) -> str:
"""Translate a pluralized key using its count category.
Categories are ``zero`` for 0, ``one`` for 1, ``many`` for values
greater than 1, and ``none`` when count is ``None``. If that category
is missing from the active language, the same category is tried in
``count`` may be an integer or a float, positive or negative. The
category is chosen from its absolute value: ``zero`` for 0 (including
``-0.0``), ``one`` for exactly 1 (so also for -1 and 1.0), and ``many``
for every other value (for example 2, -2, 0.5, -1.5 or 2.5). The
category ``none`` is used when count is ``None``. If that category is
missing from the active language, the same category is tried in
English before ``default`` and the key itself.
"""
if count is None:
category = "none"
elif count == 0:
category = "zero"
elif count == 1:
category = "one"
elif count > 1:
category = "many"
else:
raise ValueError("count must be nonnegative or None")
magnitude = abs(count)
if magnitude == 0:
category = "zero"
elif magnitude == 1:
category = "one"
else:
category = "many"
value = self._translations.get(key)
text: str | None = None
+78 -10
View File
@@ -30,17 +30,51 @@ def test_category_selection(manager, count, expected):
assert manager.p("files.found", count) == expected
@pytest.mark.parametrize("count", [-1, -100, -0.5])
def test_negative_counts_raise_value_error(manager, count):
with pytest.raises(ValueError):
@pytest.mark.parametrize(
("count", "expected"),
[
(-1, "One file"),
(-1.0, "One file"),
(-0.0, "No files"),
(-2, "-2 files"),
(-100, "-100 files"),
(-0.5, "-0.5 files"),
(-1.5, "-1.5 files"),
(0.5, "0.5 files"),
(1.5, "1.5 files"),
(0.999, "0.999 files"),
(1.001, "1.001 files"),
(1e-9, "1e-09 files"),
(10**9 + 0.5, "1000000000.5 files"),
],
)
def test_negative_and_fractional_counts(manager, count, expected):
assert manager.p("files.found", count) == expected
@pytest.mark.parametrize("count", [float("inf"), float("-inf"), float("nan")])
def test_non_finite_counts_use_many(manager, count):
assert manager.p("files.found", count) == f"{count} files"
def test_negative_count_does_not_raise_for_unknown_key(manager):
assert manager.p("unknown.key", -1) == "unknown.key"
assert manager.p("unknown.key", -2.5, default="{count} things") == "-2.5 things"
@pytest.mark.parametrize("count", [-1, -2.5, 0.5, 1.5])
def test_negative_and_fractional_counts_use_active_language(manager, count):
manager.set_language("de")
expected = "Eine Datei" if abs(count) == 1 else f"{count} Dateien"
assert manager.p("files.found", count) == expected
@pytest.mark.parametrize("count", ["3", "many", [1]])
def test_non_numeric_count_raises_type_error(manager, count):
with pytest.raises(TypeError):
manager.p("files.found", count)
def test_negative_count_raises_even_for_unknown_key(manager):
with pytest.raises(ValueError):
manager.p("unknown.key", -1)
def test_returns_string(manager):
assert isinstance(manager.p("files.found", 3), str)
@@ -94,9 +128,35 @@ def test_every_hash_count_occurrence_is_replaced(placeholders):
assert placeholders.p("twice", 4) == "4 of 4"
def test_hash_count_inserts_negative_and_fractional_counts(placeholders):
assert placeholders.p("twice", -4) == "-4 of -4"
assert placeholders.p("twice", 2.5) == "2.5 of 2.5"
assert placeholders.p("mixed", -3) == "-3 files (-3)"
@pytest.mark.parametrize(
("count", "expected"),
[(0, "Total: 0"), (1, "Total: 1"), (9, "Total: 9"), (None, "Total: None")],
[(2.5, "2.50 files"), (-2, "-2.00 files"), (-1, "-1.00 file"), (0.125, "0.12 files")],
)
def test_count_placeholder_supports_format_specification(env, count, expected):
env.install("en", {
"language": "English",
"measured": {"one": "{count:.2f} file", "many": "{count:.2f} files"},
})
assert env.make().p("measured", count) == expected
@pytest.mark.parametrize(
("count", "expected"),
[
(0, "Total: 0"),
(1, "Total: 1"),
(9, "Total: 9"),
(-1, "Total: -1"),
(-2.5, "Total: -2.5"),
(0.5, "Total: 0.5"),
(None, "Total: None"),
],
)
def test_plain_string_is_used_for_every_category(placeholders, count, expected):
assert placeholders.p("plain", count) == expected
@@ -117,7 +177,15 @@ def fallback(env):
@pytest.mark.parametrize(
("count", "expected"),
[(0, "No files"), (1, "One file"), (3, "3 files"), (None, "Count missing")],
[
(0, "No files"),
(1, "One file"),
(-1, "One file"),
(3, "3 files"),
(-3, "-3 files"),
(0.5, "0.5 files"),
(None, "Count missing"),
],
)
def test_falls_back_to_english_categories(fallback, count, expected):
fallback.set_language("fr")