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
+19 -8
View File
@@ -113,15 +113,26 @@ from pathlib import Path
from ki18n import Ki18n
manager = Ki18n(
default_language="en",
project_root=Path(__file__).resolve().parent,
)
```
The default language is `en`. Each language's display name is read from the
If `default_language` is omitted (or `None`), the language of the operating
system locale (`Ki18n.get_locale().id`, see
[Detect the system locale](#detect-the-system-locale)) is used, provided a
`strings.json` for it exists. A regional locale falls back to its parent: `de_AT`
selects `de` if there is no `de_AT`. If the locale cannot be determined or matches
no available language, `DEFAULT_LANGUAGE` (`en`) is used. Pass
`default_language="en"` (or any other language ID) to disable the detection and
always start in that language.
Each language's display name is read from the
`language` entry in its `strings.json`. The default language folder and its
valid `strings.json` must exist under `<project_root>/i18n/` during
construction. Language folders under the user data tree can add languages to
construction when it is used, that is when `default_language` is passed or
the system locale yields no available language. A language that was chosen
from the system locale only has to provide a `strings.json` (installed or in the
user folder). Language folders under the user data tree can add languages to
the discovered mapping or override the display name for an installed language.
`Ki18n` is a process-wide singleton. Only the first successful construction
@@ -140,7 +151,7 @@ The application installation resources are then read from
```python
language = i18n.get_language()
default = i18n.get_default_language()
default = i18n.get_default_language() # explicit, system locale or DEFAULT_LANGUAGE
languages = i18n.get_available_languages()
i18n.set_language("de")
@@ -165,12 +176,12 @@ locale = Ki18n.get_locale() # no manager needed; also i18n.get_locale()
if locale is not None:
print(locale.id) # "de_DE"
print(locale.language, locale.region, locale.encoding) # de DE UTF-8
try:
i18n.set_language(locale.id) # "de_DE" selects "de" if only "de" exists
except ValueError:
pass # language not available: keep the default
```
The manager uses this locale automatically when it is constructed without
`default_language`, so there is normally no need to call `set_language(locale.id)`
yourself at startup.
`get_locale()` describes the locale currently set in the operating system and
works on Linux, macOS (Darwin) and Windows. It returns a frozen `SystemLocale`
or `None` when no locale can be determined or the system uses the `C`/`POSIX`