11 KiB
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:
<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:
{
"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 of the application root returned by
ki18n.paths.bundle_root() when project_root is omitted). In a frozen
(PyInstaller) build the name of the executable is used instead of the name of
the temporary extraction directory.
- Linux and other Unix-like systems:
$XDG_DATA_HOME/<app-name>/i18n/, or~/.local/share/<app-name>/i18n/whenXDG_DATA_HOMEis unset. - macOS:
~/Library/Application Support/<app-name>/i18n/whenXDG_DATA_HOMEis 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:
{
"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
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 the application root returned by
ki18n.paths.bundle_root(): in a frozen (PyInstaller) build sys._MEIPASS,
otherwise the nearest directory that contains an i18n/ folder, searching from
the directory of sys.argv[0] upwards (or that directory itself if none
contains one). The result does not depend on where ki18n itself is located.
The application installation resources are then read from
<project_root>/i18n/.
Read and change the language
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.
Detect the system locale
from ki18n import Ki18n
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
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
locale. The result is not cached and does not change the active language.
| Field | Meaning |
|---|---|
raw |
Value as reported by the system, e.g. de_DE.UTF-8 (POSIX), de_DE (macOS), de-DE (Windows) |
id |
Normalized language ID (de_DE), accepted by set_language() |
language, script, region |
Parts of id (de, None, DE); script and region may be None |
encoding |
Character encoding from raw (UTF-8) or None |
source |
Where the value came from (see below) |
Sources, in order:
- Linux and other POSIX systems: the first non-empty of
LC_ALL,LC_MESSAGES,LANG. If it names a real locale, theLANGUAGEpriority list (colon separated, as used bygettext) takes precedence (sourceisLANGUAGE). - macOS: the same environment variables first (they are set by Terminal);
if they name no usable locale, e.g. in GUI applications, the system settings
AppleLocaleand thenAppleLanguages(read withdefaults read -g). - Windows:
GetUserDefaultLocaleName(user locale), thenGetUserDefaultUILanguage(user interface language). Environment variables are ignored.
Translate strings
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:
- Current language.
- English.
- The supplied
default. - 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
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
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
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:
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 emptylanguagemetadata, plural entries missingoneormany, or a negative plural count.FileNotFoundError: the internal default language folder or itsstrings.jsonis 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 and
pytest-asyncio; 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:
uv sync # or: pip install -e . --group dev
uv run pytest # or: python3 -m pytest