Files
ki18n/doc/API.md
T

22 KiB

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 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
  2. Concepts
  3. Resource files
  4. ki18n.ki18n module reference
  5. Resolution rules
  6. Textual dialogs
  7. ki18n.paths module reference
  8. Errors and logging
  9. Known limitations

1. Quick start

Project layout:

my-app/
├── main.py
└── i18n/
    ├── en/
    │   ├── strings.json
    │   └── help.md
    └── de/
        ├── strings.json
        └── help.md

i18n/en/strings.json:

{
  "language": "English",
  "greeting": "Hello, {name}!",
  "files.found": {
    "zero": "No files found",
    "one": "One file found",
    "many": "#count files found"
  }
}

main.py:

from ki18n import Ki18n, i18n

# Optional: configure the manager before the first translation is requested.
Ki18n("en")                      # default language; project_root is bundle_root()

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. Ki18n, i18n and I18n are re-exported by the package, so from ki18n import Ki18n, i18n works. The submodule path from ki18n.ki18n import ... remains valid.


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

<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.

{
  "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).

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:

{ "greeting": "Moin, {name}!" }

To add a whole new language, provide a complete file including language:

{ "language": "Français", "greeting": "Bonjour, {name} !" }

Keys missing from a new language fall back to English.


4. ki18n.ki18n module reference

from ki18n import Ki18n, i18n, I18n                       # package-level exports
from ki18n.ki18n import ki18n, DEFAULT_LANGUAGE           # submodule-only names

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. Only I18n is exported by the package; ki18n would shadow the submodule ki18n.ki18n, so import it from the submodule.

class Ki18n

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, ki18n.paths.bundle_root() 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.

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. Modifying the returned dictionary has no effect on the manager.

>>> 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. 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().

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).

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 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.

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 Esc; the dismiss result is None.
  • Widget IDs: #help-title, #help-text, #help-close.
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 Esc).
  • 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.
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 locating the application. They are independent of Ki18n.

from ki18n.paths import bundle_root, is_frozen

is_frozen() -> bool

True inside a PyInstaller-built executable (sys.frozen is set).

bundle_root() -> Path

Returns the root directory of the application that uses ki18n. The result never depends on where ki18n itself is located: the library may be a top-level package, vendored several directories deep inside the application (app/lib/vendor/ki18n/...) or installed in a virtual environment.

Situation Result
Frozen, sys._MEIPASS set Path(sys._MEIPASS)
Frozen, no _MEIPASS Directory of sys.executable
Not frozen Nearest directory containing an i18n/ folder, searching from the main program's directory upwards (see below)
Not frozen, no i18n/ found Directory of the main program

How the non-frozen case works:

  1. The main program's directory is the directory of sys.argv[0] (symlinks and relative paths resolved). Without a script (interactive session, python -c ...) the current working directory is used.
  2. Starting there, the directory itself and then each parent directory is checked for an i18n/ folder; the first match is the application root. This also works when the entry point lives in a subfolder such as tools/cli/main.py.
  3. If no directory on that path contains i18n/, the main program's directory is returned.

Notes:

  • The nearest match wins: with root/i18n and root/app/i18n, a program started from root/app/ gets root/app.
  • For installed console scripts (sys.argv[0] points into a virtual environment's bin/ directory) pass project_root explicitly instead.
  • Ki18n uses bundle_root() as the default project_root, so the two always agree. Pass project_root explicitly to override it.

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.

  • 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.