Added handling of system locale

This commit is contained in:
2026-11-21 11:50:47 +01:00
parent 12b471f641
commit 16d17ac6df
7 changed files with 798 additions and 29 deletions
+73 -1
View File
@@ -199,7 +199,7 @@ Keys missing from a new language fall back to English.
## 4. `ki18n.ki18n` module reference
```python
from ki18n import Ki18n, i18n, I18n # package-level exports
from ki18n import Ki18n, i18n, I18n, SystemLocale # package-level exports
from ki18n.ki18n import ki18n, DEFAULT_LANGUAGE # submodule-only names
```
@@ -210,6 +210,7 @@ from ki18n.ki18n import ki18n, DEFAULT_LANGUAGE # submodule-only names
| `DEFAULT_LANGUAGE` | `"en"`. Default value of the `default_language` parameter. |
| `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). |
| `I18n`, `ki18n` | Compatibility aliases for `Ki18n`. Only `I18n` is exported by the package; `ki18n` would shadow the submodule `ki18n.ki18n`, so import it from the submodule. |
### `class Ki18n`
@@ -283,6 +284,73 @@ no effect on the manager.
{'en': 'English', 'de': 'Deutsch', 'fr': 'Français'}
```
#### `get_locale() -> SystemLocale | None`
A `staticmethod` that describes the operating system's **currently set locale**.
It works on Linux (and other POSIX systems), macOS (Darwin) and Windows, does
not need a constructed manager (`Ki18n.get_locale()`; `manager.get_locale()` and
`i18n.get_locale()` work as well), is not cached and does not change the active
language.
Returns a [`SystemLocale`](#class-systemlocale), or `None` if no locale can be
determined or the system uses the `C`/`POSIX` locale.
Where the value comes from:
| Platform | Sources, in order |
| --- | --- |
| Linux and other POSIX | First non-empty of `LC_ALL`, `LC_MESSAGES`, `LANG`; if it names a real locale, the first usable entry of the `LANGUAGE` list takes precedence. |
| macOS | The same environment variables; if they name no usable locale (e.g. GUI applications), `defaults read -g AppleLocale`, then `defaults read -g AppleLanguages` (first usable entry). |
| Windows | `GetUserDefaultLocaleName` (user locale), then `GetUserDefaultUILanguage` (user interface language). Environment variables are ignored. |
Rules for the environment variables:
- The first non-empty variable of `LC_ALL`, `LC_MESSAGES`, `LANG` decides, even
if its value is unusable (then the result is `None`).
- `C`, `POSIX` and their variants (`C.UTF-8`, `POSIX.UTF-8`) mean "no locale".
In that case `LANGUAGE` is ignored, as in `gettext`.
- Empty and unusable `LANGUAGE` entries are skipped.
- Modifiers such as `@euro` and `@latin` do not influence `id`.
```python
>>> locale = Ki18n.get_locale()
>>> locale
SystemLocale(raw='de_DE.UTF-8', id='de_DE', language='de', script=None,
region='DE', encoding='UTF-8', source='LANG')
>>> str(locale)
'de_DE'
```
Typical use: start in the user's language if it is available.
```python
locale = Ki18n.get_locale()
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
```
On macOS the `defaults` tool is started as a subprocess (5 second timeout) when
the environment gives no answer; if it fails, the result is `None`.
#### `class SystemLocale`
Frozen dataclass (hashable, comparable) returned by `get_locale()`.
| Field | Type | Description |
| --- | --- | --- |
| `raw` | `str` | Value exactly as reported by the system (whitespace stripped), e.g. `"de_DE.UTF-8"`, `"de_DE"` (macOS), `"de-DE"` (Windows). |
| `id` | `str` | Normalized language ID (see [Language IDs](#language-ids)), e.g. `"de_DE"`, `"zh_Hans_CN"`. Accepted by `set_language()`. |
| `language` | `str` | Language part of `id`, e.g. `"de"`. |
| `script` | `str \| None` | Script part (four letters, title case), e.g. `"Hans"`. |
| `region` | `str \| None` | Region part (`"DE"` or three digits such as `"419"`). |
| `encoding` | `str \| None` | Encoding part of `raw` (`"UTF-8"`), `None` if the system reports none (always on macOS and Windows). |
| `source` | `str` | `"LC_ALL"`, `"LC_MESSAGES"`, `"LANG"`, `"LANGUAGE"`, `"AppleLocale"`, `"AppleLanguages"`, `"GetUserDefaultLocaleName"` or `"GetUserDefaultUILanguage"`. |
`str(locale)` returns `id`.
#### `set_language(code: str) -> None`
Activates a language and notifies the listeners.
@@ -600,6 +668,10 @@ These points are based on reading the current source code.
- **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`.
- **System locale on POSIX is environment based.** `get_locale()` reads the
environment of the running process. Locale settings that are only stored in
files such as `/etc/locale.conf` and not exported to the process are not seen
on Linux.
- **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