Files
ki18n/README.md
T
2026-11-20 21:35:24 +01:00

260 lines
8.7 KiB
Markdown

# ki18n
Reusable, file-backed internationalization for Python applications. Translation
strings and program help are stored outside Python source in language-specific
resource folders. The selected language is set by the operating system locale
and can be overridden by the user.
## Resource layout
Each language folder can contain `strings.json` and `help.md`:
```text
<resource-root>/i18n/
├── en/
│ ├── strings.json
│ └── help.md
├── de/
│ ├── strings.json
│ └── help.md
├── de_DE/
│ ├── strings.json
│ └── help.md
└── de_AT/
├── strings.json
└── help.md
```
Each language folder must include `strings.json` with a non-empty `language`
entry. The folder name is the language ID and the `language` value is its
display name. `get_available_languages()` discovers this mapping from both
the user data and installed `i18n` trees.
To use the included textual dialogs the strings.json must include the
following entries in all supported languages:
```json
{
"language": "English",
"app.title": "Sample application",
"title_select_language": "Select language",
"title_help": "Example help",
"btn_close": "Close",
"btn_cancel": "Cancel",
"msg_help_missing": "Help file is missing!",
}
```
The library searches the user's application data tree first, then the
application's installation tree. The application name is the name of
`project_root` (or the directory containing the executed program when
`project_root` is omitted).
- Linux and other Unix-like systems: `$XDG_DATA_HOME/<app-name>/i18n/`, or
`~/.local/share/<app-name>/i18n/` when `XDG_DATA_HOME` is unset.
- macOS: `~/Library/Application Support/<app-name>/i18n/` when
`XDG_DATA_HOME` is unset.
- Windows: `%LOCALAPPDATA%/<app-name>/i18n/`.
- Installation resources: `<project_root>/i18n/`.
User resources take precedence over installed resources. Language discovery
checks the user data tree first, then the installed tree; when both contain
the same language, the user data `language` value is used. The user data may
contain only a subset of the language strings if the language strings at the
project root contain the complete translations.
The default language must still have an installed folder and `strings.json`.
Within each resource tree, locale lookup tries the most specific ID and then
its parents. For example, `de_CH` tries `de_CH`, then `de`; `de_DE.UTF-8` is
normalized to `de_DE`, then tries `de`. Language IDs are case-insensitive.
Hyphens are accepted as separators, and the returned language ID is normalized
(for example, `DE-de.utf8` becomes `de_DE`). When the requested language is not
configured, the returned ID is the most specific configured parent language.
For example, with only `de` configured, `set_language("de_CH")` selects `de`.
## Translation files
`strings.json` is a flat keyspace. Values are either strings or plural objects:
```json
{
"language": "English",
"button.save": "Save",
"status.generated": "Generated: {files}",
"files.found": {
"zero": "No files",
"one": "One file",
"many": "#count files"
}
}
```
Plural objects must include `one` and `many`. The `zero` and `none` categories
are optional; if omitted, each defaults to that entry's `many` text. `p()`
replaces `#count` and formats `{count}` along with any other keyword
placeholders.
## Help
The help.md is a complete document that contains all the help as markdown.
It also is located in the country specific folders and can be overwritten
by the user. It may be displayed with the textual class HelpScreen.
## API
### Create and configure the manager
```python
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
`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
the discovered mapping or override the display name for an installed language.
`Ki18n` is a process-wide singleton. Only the first successful construction
initializes it; later calls return that same instance and ignore their
configuration arguments. Configure it once near application startup.
If omitted, `project_root` is derived from the directory containing
`sys.argv[0]`. The application installation resources are then read from
`<project_root>/i18n/`.
### Read and change the language
```python
language = i18n.get_language()
default = i18n.get_default_language()
languages = i18n.get_available_languages()
i18n.set_language("de")
```
`get_available_languages()` returns a copy of the mapping discovered from
user and installed resources. Language IDs are case-insensitive. A regional
variant can be requested when its parent
language is configured, even if the regional language is not configured; for
example, `set_language("de_CH")` selects `de` when only `de` is configured.
`get_language()` then returns `de`, which can be used to index the available
languages mapping. Unknown languages raise `ValueError`. A language change
loads and validates its translation file before changing state. Selecting the
active language is a no-op.
### Translate strings
```python
save_label = i18n.t("button.save")
message = i18n.t("status.generated", files="main.py")
fallback = i18n.t("missing.key", default="Fallback text")
```
`t(key, default=None, **kwargs)` uses this fallback order:
1. Current language.
2. English.
3. The supplied `default`.
4. The key itself.
Keyword arguments are applied with `str.format()`. If formatting fails because
a placeholder is missing or the format string is invalid, the unformatted
text is returned. Calling `t()` for a plural object raises `ValueError`; use
`p()` for pluralized entries.
### Translate pluralized strings
```python
files_text = i18n.p("files.found", 3)
no_count_text = i18n.p("files.found", None)
```
`p(key, count, default=None, **kwargs)` selects a category as follows:
| Count | Category |
| --- | --- |
| `0` | `zero` |
| `1` | `one` |
| Greater than `1` | `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.
### Listen for language changes
```python
def language_changed(code: str) -> None:
refresh_ui()
i18n.add_language_change_listener(language_changed)
i18n.remove_language_change_listener(language_changed)
```
Listeners receive the normalized, configured language ID. Registering the same
callback twice has no additional effect. The compatibility aliases
`add_listener()` and `remove_listener()` are also available.
### Read help
```python
help_text = i18n.get_help()
```
`get_help()` returns the active language's `help.md`, following the same
regional and user-resource lookup rules. If no matching help file exists, it
tries English. If neither is available, it raises `FileNotFoundError`.
### Module-style compatibility handle
For applications that prefer the earlier module-style access, the module
exports a lazy `i18n` handle for code that prefers a module-style instance:
```python
from ki18n import Ki18n, i18n
# Configure the singleton first when custom settings are needed.
Ki18n("en", project_root="/path/to/app")
i18n.set_language("de")
print(i18n.t("button.save"))
```
The handle initializes the singleton with default settings on first use if no
`Ki18n` instance has been constructed yet. `I18n` and `ki18n` remain
available as compatibility aliases for the class.
`_get_translations()` returns a deep copy of the current translation mapping;
it is intended for compatibility and inspection rather than normal lookup.
## Errors
- `ValueError`: unknown language, invalid JSON, invalid translation structure,
missing or empty `language` metadata, plural entries missing `one` or
`many`, or a negative plural count.
- `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.
## Tests
The test suite uses [pytest](https://docs.pytest.org/) and
[pytest-asyncio](https://pytest-asyncio.readthedocs.io/); the Textual dialogs are
driven with Textual's `Pilot`. Tests create temporary application and user-data
directories and do not access real user language resources.
Install the development dependencies and run the tests from the repository root:
```sh
uv sync # or: pip install -e . --group dev
uv run pytest # or: python3 -m pytest
```