Files
ki18n/doc/API.md
T

621 lines
22 KiB
Markdown

# ki18n API Documentation
ki18n is a small, file-backed internationalization library for Python
applications. Translations live in plain JSON files, can be overridden per user
without touching the installed application, and can be consumed through a
process-wide manager (`Ki18n`) or ready-made [Textual](https://textual.textualize.io/)
dialogs.
- Python: 3.10 or newer
- Runtime dependency: `textual` (only needed for the dialogs in
`ki18n.help_screen` and `ki18n.language_select_screen`; `ki18n.ki18n` itself
uses the standard library only)
## Contents
1. [Quick start](#1-quick-start)
2. [Concepts](#2-concepts)
3. [Resource files](#3-resource-files)
4. [`ki18n.ki18n` module reference](#4-ki18nki18n-module-reference)
5. [Resolution rules](#5-resolution-rules)
6. [Textual dialogs](#6-textual-dialogs)
7. [`ki18n.paths` module reference](#7-ki18npaths-module-reference)
8. [Errors and logging](#8-errors-and-logging)
9. [Known limitations](#9-known-limitations)
---
## 1. Quick start
Project layout:
```text
my-app/
├── main.py
└── i18n/
├── en/
│ ├── strings.json
│ └── help.md
└── de/
├── strings.json
└── help.md
```
`i18n/en/strings.json`:
```json
{
"language": "English",
"greeting": "Hello, {name}!",
"files.found": {
"zero": "No files found",
"one": "One file found",
"many": "#count files found"
}
}
```
`main.py`:
```python
from ki18n.ki18n import Ki18n, i18n
# Optional: configure the manager before the first translation is requested.
Ki18n("en") # default language; project_root is derived from sys.argv[0]
print(i18n.t("greeting", name="Ada")) # Hello, Ada!
print(i18n.p("files.found", 3)) # 3 files found
i18n.set_language("de")
print(i18n.t("greeting", name="Ada")) # Hallo, Ada!
```
> **Import path.** The package's `__init__.py` is currently empty, so import
> from the submodule: `from ki18n.ki18n import Ki18n, i18n`.
---
## 2. Concepts
### Singleton manager
`Ki18n` is a process-wide singleton. Only the **first** construction has an
effect; later `Ki18n(...)` calls return the same instance and ignore their
arguments. If the first construction fails (for example because resources are
missing), the instance stays uninitialized and construction can simply be
retried.
The module-level handle `i18n` is a lazy proxy. It creates the singleton with
default arguments on first attribute access, so an application can still call
`Ki18n(...)` with its own configuration before the first use.
### Installed and user resources
Resources are read from two locations:
| Location | Path | Purpose |
| --- | --- | --- |
| Installed | `<project_root>/i18n/` | Shipped with the application. Must contain the default language. |
| User | `<local_root>/i18n/` | Optional per-user customization and additional languages. |
User resources take precedence over installed ones. `strings.json` files are
**merged key by key** (a user file may contain just the keys it wants to change
or add), whereas `help.md` is **replaced as a whole**.
### Language IDs
Language IDs are normalized before use:
| Input | Normalized |
| --- | --- |
| `en`, `EN` | `en` |
| `de-de`, `de_de`, `DE_de` | `de_DE` |
| `de_DE.UTF-8`, `de_DE@euro` | `de_DE` (encoding/modifier suffixes removed) |
| `zh-hant-tw` | `zh_Hant_TW` (script: title case, region: upper case) |
| `es_419` | `es_419` (three-digit region) |
Parts may only contain ASCII letters and digits. Anything else (empty parts,
`/`, spaces, non-strings, …) is invalid.
A regional ID falls back to progressively broader parents:
`sr_Latn_RS` → `sr_Latn` → `sr`. Folder names are matched case-insensitively
on every platform.
---
## 3. Resource files
### Directory layout
```text
<root>/i18n/<language-id>/strings.json
<root>/i18n/<language-id>/help.md (optional)
```
The folder name is a language ID (`en`, `de`, `de_AT`, …). It is normalized, so
`de-at` and `de_AT` name the same language. Two folders that normalize to the
same ID are a configuration error (an exception for installed resources, a
warning for user resources). Files directly inside `i18n/` and folders without
a `strings.json` are ignored for language discovery.
### `strings.json`
A UTF-8 encoded JSON object (a byte-order mark is not accepted). Every value is
either a **string** or a **plural object**.
```json
{
"language": "Deutsch",
"app.title": "Beispiel",
"welcome": "Willkommen, {name}!",
"files.found": {
"zero": "Keine Datei gefunden",
"one": "Eine Datei gefunden",
"many": "#count Dateien gefunden",
"none": "Anzahl unbekannt"
}
}
```
| Rule | Details |
| --- | --- |
| `language` | Display name of the language (non-empty string). Required in every installed file. Optional in user files that customize an installed language (the installed name is inherited). Required in user files that introduce a new language. |
| Keys | Arbitrary strings. Dots are only a naming convention. |
| String values | Used by `t()` (and by `p()` as a non-plural fallback). May contain `str.format` placeholders such as `{name}`. |
| Plural objects | Keys must be from `zero`, `one`, `many`, `none`; values must be strings. `one` and `many` are **mandatory**. |
| `zero` / `none` | Default to the text of `many` when omitted. |
| `#count` | Inside plural texts, replaced by the count. `{count}` works as well. |
Invalid files (bad JSON, wrong value types, missing `one`/`many`, unknown plural
categories, invalid UTF-8, …) are rejected with `ValueError`. For installed files
this is an error; for user files it is logged and the file is ignored as a
whole (see [Errors and logging](#8-errors-and-logging)).
### `help.md`
A Markdown document for the help dialog (`Ki18n.get_help()` /
`HelpScreen`). Read as UTF-8.
### Customizing as a user
To change some translations of an installed language, create
`<local_root>/i18n/<language-id>/strings.json` with only the affected keys:
```json
{ "greeting": "Moin, {name}!" }
```
To add a whole new language, provide a complete file including `language`:
```json
{ "language": "Français", "greeting": "Bonjour, {name} !" }
```
Keys missing from a new language fall back to English.
---
## 4. `ki18n.ki18n` module reference
```python
from ki18n.ki18n import Ki18n, i18n, I18n, ki18n, DEFAULT_LANGUAGE
```
### Module-level names
| Name | Description |
| --- | --- |
| `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`. |
| `I18n`, `ki18n` | Compatibility aliases for `Ki18n`. |
### `class Ki18n`
```python
Ki18n(
default_language: str = "en",
project_root: str | Path | None = None,
local_root: str | Path | None = None,
)
```
Creates (or returns) the singleton manager and loads the 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"`). |
| `project_root` | Application directory that contains the installed `i18n/` folder. `~` is expanded. If omitted, the directory of `sys.argv[0]` is used (relative paths are resolved against the current working directory). |
| `local_root` | The application's per-user directory; user resources are read from its `i18n/` subfolder. `~` is expanded. If omitted: `<user data dir>/<name of project_root>` (see below). |
Default user data directory (used when `local_root` is omitted):
| Platform | Directory |
| --- | --- |
| Windows | `%LOCALAPPDATA%`, otherwise `~/AppData/Local` |
| Linux and other POSIX | `$XDG_DATA_HOME`, otherwise `~/.local/share` |
| macOS | `$XDG_DATA_HOME`, otherwise `~/Library/Application Support` |
**Raises**
| 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. |
| `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. |
| `project_root` | `Path` | Resolved application directory. |
| `i18n_root` | `Path` | `project_root / "i18n"`. |
| `local_root` | `Path` | Per-user directory. |
| `available_languages` | `dict[str, str]` | Language ID → display name, in discovery order. Prefer `get_available_languages()`. |
The manager is not synchronized: it performs no locking, so use it from one
thread or guard calls externally.
---
#### `get_language() -> str`
Returns the ID of the active language (always one of the keys of
`get_available_languages()`).
#### `get_default_language() -> str`
Returns the normalized default language passed to the constructor.
#### `get_available_languages() -> dict[str, str]`
Returns a new dictionary that maps language IDs to display names. The default
language comes first, the rest is sorted by display name (case-insensitive).
Languages come from the installed folder and the user folder; see
[Resolution rules](#5-resolution-rules). Modifying the returned dictionary has
no effect on the manager.
```python
>>> i18n.get_available_languages()
{'en': 'English', 'de': 'Deutsch', 'fr': 'Français'}
```
#### `set_language(code: str) -> None`
Activates a language and notifies the listeners.
1. `code` is normalized. An invalid ID raises `ValueError`.
2. If the language is not available, the most specific available parent is used
(`de_CH` → `de`). If none is available, `ValueError("Unknown language: ...")`
is raised.
3. If the resolved language is already active, nothing happens (no reload, no
notification).
4. The language's files are loaded and validated **before** the state changes.
If loading fails (`FileNotFoundError` or `ValueError`), the previous language
stays active and no listener is called.
5. Listeners are called with the resolved language ID.
Translations are read from disk on each actual switch, so changes to files
become visible after switching away and back.
#### `t(key: str, default: str | None = None, **kwargs) -> str`
Translates a simple (non-plural) key.
Lookup order: active language → English → `default` → `key` itself.
If keyword arguments are given, the text is formatted with `str.format`. When the
text is malformed or a placeholder value is missing, the unformatted text is
returned instead of raising (see [Known limitations](#9-known-limitations)).
Without keyword arguments no formatting takes place, so `{{`/`}}` stay as they
are. The formatting also applies to the `default` text and to the key fallback.
An empty string is a valid translation and is returned as is.
**Raises** `ValueError` if the key refers to a plural object; use `p()`.
```python
i18n.t("welcome", name="Ada") # "Welcome, Ada!"
i18n.t("missing.key") # "missing.key"
i18n.t("missing.key", default="Fallback") # "Fallback"
i18n.t("wert", n=42) # formats e.g. "{n:05d}" -> "00042"
```
#### `p(key: str, count: int | float | None, default: str | None = None, **kwargs) -> str`
Translates a pluralized key.
The category is chosen from `count`:
| `count` | Category |
| --- | --- |
| `None` | `none` |
| `0` | `zero` |
| `1` | `one` |
| greater than 1 | `many` |
Lookup order: active language → English (same category) → `default` → `key`.
A plain string value is also accepted and used for every category, which helps
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.
**Raises** `ValueError` for negative counts (checked before the lookup).
```python
i18n.p("files.found", 0) # "No files found"
i18n.p("files.found", 1) # "One file found"
i18n.p("files.found", 5) # "5 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
```
#### `get_help() -> str`
Returns the Markdown help text of the active language, falling back to the
English help text if the active language has none. See
[Resolution rules](#5-resolution-rules) for the search order. The file is read
on every call.
**Raises** `FileNotFoundError` if no help file is found.
#### `add_language_change_listener(callback: Callable[[str], None]) -> None`
Registers a callback that is called with the new language ID after each
successful change of the active language. Registering the same callback again
has no effect.
Details:
- Callbacks run synchronously, in registration order, after the new language is
active (calling `t()` inside a callback returns the new texts).
- A callback may remove itself while it is being notified.
- Exceptions raised by a callback propagate out of `set_language()`; the new
language is already active at that point and later callbacks are not called.
#### `remove_language_change_listener(callback: Callable[[str], None]) -> None`
Unregisters a callback. Removing a callback that is not registered is harmless.
#### `add_listener` / `remove_listener`
Compatibility aliases for the two methods above.
#### Internal helpers
Names starting with an underscore (for example `_get_translations()`, which
returns a deep copy of the active translation mapping) are not part of the
public API and may change.
---
## 5. Resolution rules
### Available languages
1. All folders in the user and installed `i18n/` roots are scanned.
2. A language is **available** if its folder contains a valid `strings.json`
with a non-empty `language` entry.
3. The display name comes from the user file if it defines one, otherwise from
the installed file. A user file without `language` that customizes an
installed language inherits the installed name.
4. A user folder for a language that is **not** installed and whose file lacks
`language` is ignored with a warning.
5. Invalid **user** folders and files are ignored with a warning. Invalid
**installed** folders and files raise `ValueError`.
### Loading a language (`strings.json`)
For a language such as `de_AT`, files are merged from lowest to highest
priority:
1. installed `de`
2. installed `de_AT`
3. user `de`
4. user `de_AT`
Later files override earlier ones key by key. A plural object replaces the whole
installed entry for that key. If no file exists for the language,
`FileNotFoundError` is raised.
### Finding a single file (`help.md`)
The first existing file wins, in this order (for `de_AT`):
1. user `de_AT`
2. user `de`
3. installed `de_AT`
4. installed `de`
If nothing is found and the language is not English, the same search is repeated
for `en`. Otherwise `FileNotFoundError` is raised.
### Translating a key
`t()` and `p()`: active language (all merged layers) → English (merged the same
way; optional when another default language is used and no English resources
exist) → `default` argument → the key.
---
## 6. Textual dialogs
Both dialogs are `textual.screen.ModalScreen` subclasses that read their texts
from the active language through `i18n`. They require `textual` to be installed.
```python
from ki18n.help_screen import HelpScreen
from ki18n.language_select_screen import LanguageSelectScreen
```
### Required translation keys
| Key | Used by | Meaning |
| --- | --- | --- |
| `title_select_language` | `LanguageSelectScreen` | Dialog title. |
| `btn_cancel` | `LanguageSelectScreen` | Cancel button label. |
| `title_help` | `HelpScreen` | Dialog title. |
| `btn_close` | `HelpScreen` | Close button label. |
| `msg_help_missing` | `HelpScreen` | Shown instead of the help text when no `help.md` exists. |
Missing keys fall back to English and finally to the key name.
### `HelpScreen(toc: bool = True)`
`ModalScreen[None]`. Shows `i18n.get_help()` in a scrollable Markdown viewer.
| Parameter | Description |
| --- | --- |
| `toc` | Show the Markdown table of contents. |
- Closes with the **Close** button or <kbd>Esc</kbd>; the dismiss result is `None`.
- Widget IDs: `#help-title`, `#help-text`, `#help-close`.
```python
self.push_screen(HelpScreen())
self.push_screen(HelpScreen(toc=False))
```
### `LanguageSelectScreen()`
`ModalScreen[str | None]`. Shows one button per available language (in the order
of `get_available_languages()`); the active language is highlighted with the
`primary` button variant.
- Result: the selected language ID (for example `"de"` or `"de_AT"`), or `None`
if the dialog is cancelled (**Cancel** button or <kbd>Esc</kbd>).
- The dialog does **not** change the language itself; apply the result with
`i18n.set_language()`.
- Widget IDs: `#language-dialog`, `#language-title`, `#language-options`,
`#lang-<language-id>` (for example `#lang-de_AT`), `#language-dialog-buttons`,
`#language-cancel`.
```python
from textual.app import App
class MyApp(App):
def action_choose_language(self) -> None:
def apply(selected: str | None) -> None:
if selected is not None and selected != i18n.get_language():
i18n.set_language(selected)
self.push_screen(LanguageSelectScreen(), apply)
```
Dialogs read their texts when they are composed, so they show the language that
is active when they are opened. To refresh your own widgets after a change,
register a language-change listener.
---
## 7. `ki18n.paths` module reference
Small helpers for applications that are bundled with PyInstaller and for locating
per-user data directories. They are independent of `Ki18n` (which uses
`base_data_dir()` for its default user directory).
#### `is_frozen() -> bool`
`True` inside a PyInstaller-built executable (`sys.frozen` is set).
#### `bundle_root() -> Path`
Directory that contains the bundled application files at runtime:
| Situation | Result |
| --- | --- |
| Frozen, `sys._MEIPASS` set | `Path(sys._MEIPASS)` |
| Frozen, no `_MEIPASS` | Directory of `sys.executable` |
| Source checkout | Parent of the `ki18n` package directory |
For a frozen application, pass `bundle_root()` as `project_root` if the `i18n/`
folder is bundled there:
```python
from ki18n.paths import bundle_root
Ki18n("en", project_root=bundle_root())
```
#### `base_data_dir() -> Path`
Conventional per-user base directory for application data. The directory is
neither created nor checked for existence.
| Platform | Result |
| --- | --- |
| Windows | `%LOCALAPPDATA%`, else `~/AppData/Local` |
| macOS (Darwin) | `$XDG_DATA_HOME` if set, else `~/Library/Application Support` |
| Linux and other POSIX | `$XDG_DATA_HOME` if set, else `~/.local/share` |
An empty environment variable counts as unset; a leading `~` in `XDG_DATA_HOME`
is expanded.
#### `data_dir(name: str) -> Path`
Data directory of the application called `name`: `base_data_dir() / name`, for
example `data_dir("ki18n")` is `~/.local/share/ki18n` on Linux. The directory is
not created.
Raises `ValueError` if `name` is empty, `.` or `..`, or contains `/` or `\`.
```python
from ki18n.paths import data_dir
Ki18n("en", local_root=data_dir("my-app"))
```
---
## 8. Errors and logging
### Exceptions
| Exception | Raised by | Cause |
| --- | --- | --- |
| `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` | `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. |
| `FileNotFoundError` | `get_help` | No help file for the active language or English. |
After any exception from `set_language`, the previously active language remains
in effect.
### Logging
The library logs through the standard `logging` module, logger name
`ki18n.ki18n`. Problems in **user** resources never stop the application; they
are reported at `WARNING` level and the offending file or folder is ignored:
- `Custom language folder <path> ignored: ...` (invalid or duplicate folder name)
- `Custom translation file <path> ignored: ...` (invalid file)
- `Custom language '<id>' ignored: ...` (new language without a `language` entry)
---
## 9. Known limitations
These points are based on reading the current source code.
- **No package-level exports.** `ki18n/__init__.py` is empty, so
`from ki18n import Ki18n, i18n` does not work; use `ki18n.ki18n`.
- **Narrow format error handling.** `t()`/`p()` only swallow `KeyError`,
`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`.
- **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
the installed file and no translation of individual sections.
- **Documentation drift in the source.** The module and constructor docstrings
mention a `key_aliases` mapping, which the code does not implement.