Updated bundle_root to work wherever ithe root is in relation to the library

This commit is contained in:
2026-11-21 09:57:55 +01:00
parent a419167939
commit 94f220e00d
4 changed files with 224 additions and 67 deletions
+52 -43
View File
@@ -58,7 +58,7 @@ my-app/
`main.py`:
```python
from ki18n.ki18n import Ki18n, i18n
from 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]
@@ -70,8 +70,9 @@ 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`.
> **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.
---
@@ -198,7 +199,8 @@ 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
from ki18n import Ki18n, i18n, I18n # package-level exports
from ki18n.ki18n import ki18n, DEFAULT_LANGUAGE # submodule-only names
```
### Module-level names
@@ -208,7 +210,7 @@ from ki18n.ki18n import Ki18n, i18n, I18n, ki18n, DEFAULT_LANGUAGE
| `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`. |
| `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`
@@ -307,7 +309,7 @@ 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)).
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.
@@ -326,17 +328,14 @@ i18n.t("wert", n=42) # formats e.g. "{n:05d}" -> "0004
Translates a pluralized key.
`count` may be an `int` or a `float`, positive or negative. The category is
chosen from its **absolute value**:
The category is chosen from `count`:
| `count` | Category |
| --- | --- |
| `None` | `none` |
| `0`, `0.0`, `-0.0` | `zero` |
| `1`, `1.0`, `-1` | `one` |
| any other number, e.g. `2`, `-2`, `0.5`, `-1.5`, `2.5` | `many` |
Values such as `NaN` and infinity also select `many`.
| `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
@@ -345,18 +344,14 @@ 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. `#count` inserts the count as Python prints it (`2.5`, `-3`); use a
format specification such as `{count:.1f}` to control the number format.
replaced.
**Raises** `TypeError` if `count` is neither a number nor `None`.
**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", -1) # "One file found" (absolute value)
i18n.p("files.found", 5) # "5 files found"
i18n.p("files.found", 2.5) # "2.5 files found"
i18n.p("files.found", -2) # "-2 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
```
@@ -521,9 +516,11 @@ 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).
Small helpers for locating the application. They are independent of `Ki18n`.
```python
from ki18n.paths import bundle_root, is_frozen
```
#### `is_frozen() -> bool`
@@ -531,27 +528,48 @@ per-user data directories. They are independent of `Ki18n` (which uses
#### `bundle_root() -> Path`
Directory that contains the bundled application files at runtime:
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 | Parent of the `ki18n` package directory |
| 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 |
When `ki18n` is installed as a package, "not frozen" means the directory that
contains the package (for example `site-packages`), not your application
directory. In that case pass `project_root` explicitly.
How the non-frozen case works:
For a frozen application, pass `bundle_root()` as `project_root` if the `i18n/`
folder is bundled there:
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` itself uses the directory of `sys.argv[0]` as default `project_root`
without walking up. To use the application root also for deeper entry points,
pass it explicitly:
```python
from ki18n import Ki18n
from ki18n.paths import bundle_root
Ki18n("en", project_root=bundle_root())
```
#### `base_data_dir() -> Path`
#### `_base_data_dir() -> Path` (internal)
Conventional per-user base directory for application data. The directory is
neither created nor checked for existence.
@@ -592,7 +610,7 @@ Ki18n("en", local_root=data_dir("my-app"))
| `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. |
| `TypeError` | `p` | `count` is neither a number nor `None`. |
| `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
@@ -614,19 +632,10 @@ are reported at `WARNING` level and the offending file or folder is ignored:
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.
- **Simple plural rules.** `p()` knows only the categories `zero`, `one`, `many`
and `none`, chosen from the absolute value of the count. Language-specific
plural rules (for example separate forms for 2–4 in Slavic languages) are not
supported, and fractions such as `1.5` always use `many`.
- **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.