USe the system locale if the parameter default_language is not set while instanciating Ki18n

This commit is contained in:
2026-11-22 09:46:04 +01:00
parent 0e8875e878
commit f7825e6789
8 changed files with 420 additions and 37 deletions
+39 -12
View File
@@ -61,7 +61,8 @@ my-app/
from ki18n import Ki18n, i18n
# Optional: configure the manager before the first translation is requested.
Ki18n("en") # default language; project_root is bundle_root()
Ki18n() # default language: system locale, else "en"; project_root is bundle_root()
# Ki18n("en") # or always start in a fixed language
print(i18n.t("greeting", name="Ada")) # Hello, Ada!
print(i18n.p("files.found", 3)) # 3 files found
@@ -96,7 +97,7 @@ Resources are read from two locations:
| Location | Path | Purpose |
| --- | --- | --- |
| Installed | `<project_root>/i18n/` | Shipped with the application. Must contain the default language. |
| Installed | `<project_root>/i18n/` | Shipped with the application. Must contain `DEFAULT_LANGUAGE` (or the explicitly passed default language). |
| User | `<local_root>/i18n/` | Optional per-user customization and additional languages. |
User resources take precedence over installed ones. `strings.json` files are
@@ -207,7 +208,7 @@ from ki18n.ki18n import ki18n, DEFAULT_LANGUAGE # submodule-only names
| Name | Description |
| --- | --- |
| `DEFAULT_LANGUAGE` | `"en"`. Default value of the `default_language` parameter. |
| `DEFAULT_LANGUAGE` | `"en"`. Language used when `default_language` is omitted and the system locale yields no available language. |
| `Ki18n` | The manager class. |
| `i18n` | Lazy handle: every attribute access is forwarded to the `Ki18n` singleton, which is created with default arguments if it does not exist yet. Unknown attributes raise `AttributeError`. |
| `SystemLocale` | Frozen dataclass returned by `Ki18n.get_locale()`; see [`get_locale()`](#get_locale---systemlocale--none). |
@@ -217,17 +218,19 @@ from ki18n.ki18n import ki18n, DEFAULT_LANGUAGE # submodule-only names
```python
Ki18n(
default_language: str = "en",
default_language: str | None = None,
project_root: str | Path | None = None,
local_root: str | Path | None = None,
)
```
Creates (or returns) the singleton manager and loads the default language.
Creates (or returns) the singleton manager and loads the default language. If
`default_language` is omitted, it is derived from the system locale; see
[Default language](#default-language).
| Parameter | Description |
| --- | --- |
| `default_language` | Language that is active after construction. Also the language that is listed first and that must be shipped with the application. Normalized (`"de-at"` → `"de_AT"`). |
| `default_language` | Language that is active after construction, and the one that is listed first. Normalized (`"de-at"` → `"de_AT"`). If omitted or `None`, the language of the system locale is used when a `strings.json` exists for it, otherwise `DEFAULT_LANGUAGE`; see [Default language](#default-language). An explicitly passed language must be shipped with the application. |
| `project_root` | Application directory that contains the installed `i18n/` folder. `~` is expanded. If omitted, [`ki18n.paths.bundle_root()`](#7-ki18npaths-module-reference) is used: the application root, independent of where ki18n is located. |
| `local_root` | The application's per-user directory; user resources are read from its `i18n/` subfolder. `~` is expanded. If omitted: `<user data dir>/<application name>` (see below). The application name is the name of `project_root`; in a frozen one-file build it is the name of the executable (without extension), because the extraction directory changes on every start. |
@@ -244,14 +247,14 @@ Default user data directory (used when `local_root` is omitted):
| Exception | Condition |
| --- | --- |
| `ValueError` | `default_language` is not a valid language ID. |
| `FileNotFoundError` | The installed `i18n/` directory, the default language folder or its `strings.json` does not exist. |
| `FileNotFoundError` | The installed `i18n/` directory does not exist, or the default language is an explicitly passed language or `DEFAULT_LANGUAGE` (no matching system locale) and its installed folder or `strings.json` does not exist. |
| `ValueError` | An installed `strings.json` is invalid, lacks `language`, or two installed folders normalize to the same ID. |
**Attributes** (read them, do not modify them)
| Attribute | Type | Description |
| --- | --- | --- |
| `default_language` | `str` | Normalized default language. |
| `default_language` | `str` | Normalized default language: the explicit one, the system locale's language or `DEFAULT_LANGUAGE`. |
| `project_root` | `Path` | Resolved application directory. |
| `i18n_root` | `Path` | `project_root / "i18n"`. |
| `local_root` | `Path` | Per-user directory. |
@@ -269,7 +272,9 @@ Returns the ID of the active language (always one of the keys of
#### `get_default_language() -> str`
Returns the normalized default language passed to the constructor.
Returns the normalized default language chosen during construction: the language
passed to the constructor, otherwise the system locale's language, otherwise
`DEFAULT_LANGUAGE`.
#### `get_available_languages() -> dict[str, str]`
@@ -321,7 +326,8 @@ SystemLocale(raw='de_DE.UTF-8', id='de_DE', language='de', script=None,
'de_DE'
```
Typical use: start in the user's language if it is available.
The constructor uses this locale automatically if no `default_language` is passed
(see [Default language](#default-language)). It can also be applied later:
```python
locale = Ki18n.get_locale()
@@ -329,7 +335,7 @@ if locale is not None:
try:
i18n.set_language(locale.id) # "de_DE" selects "de" if only "de" exists
except ValueError:
pass # not available: keep the default language
pass # not available: keep the current language
```
On macOS the `defaults` tool is started as a subprocess (5 second timeout) when
@@ -465,6 +471,27 @@ public API and may change.
## 5. Resolution rules
### Default language
Applies to the first construction of `Ki18n`:
1. If `default_language` is passed, it is used as given (normalized). Its installed
folder and `strings.json` must exist, otherwise `FileNotFoundError` is raised.
The system locale is not queried.
2. Otherwise `Ki18n.get_locale()` is called. If it returns a locale, its `id` and
then its progressively broader parents are looked up in the
[available languages](#available-languages): `de_AT` tries `de_AT`, then `de`;
`sr_Latn_RS` tries `sr_Latn_RS`, `sr_Latn`, `sr`. The first one found becomes
the default language. User-only languages (a user folder with a `strings.json`
that defines `language`) count as available.
3. If `get_locale()` returns `None` (locale not determinable, or `C`/`POSIX`) or
none of the IDs is available, `DEFAULT_LANGUAGE` is used. In this case its
installed folder and `strings.json` must exist, otherwise `FileNotFoundError`
is raised.
The chosen language is the active language, is returned by
`get_default_language()` and is listed first by `get_available_languages()`.
### Available languages
1. All folders in the user and installed `i18n/` roots are scanned.
@@ -639,7 +666,7 @@ Notes:
| --- | --- | --- |
| `ValueError` | constructor | Invalid default language ID. |
| `ValueError` | constructor, `set_language` | Invalid or inconsistent **installed** resource files (bad JSON, bad value types, missing `language`, missing `one`/`many`, duplicate folders). |
| `FileNotFoundError` | constructor | Missing installed `i18n/` folder, default language folder, or its `strings.json`. |
| `FileNotFoundError` | constructor | Missing installed `i18n/` folder, or missing installed folder / `strings.json` of the explicit default language or of `DEFAULT_LANGUAGE`. |
| `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. |