Runtime library
go get locale.dev/localizerThe root package depends on Cobra (v1.8 or later), pflag, golang.org/x/text and golang.org/x/sys; the
kongx and urfave subpackages add kong and urfave/cli v3 respectively (see the kong and
urfave/cli guides). The library makes no network calls, and it has no telemetry or
credentials. The full API is on
pkg.go.dev. Until v0.6 the module path was github.com/DABH/localizer;
from v0.7.0 it is locale.dev/localizer, so a CLI that upgrades changes its imports.
Functions
Section titled “Functions”| Function | Description |
|---|---|
Localize(root *cobra.Command, catalogs fs.FS, opts ...Option) |
Translates a Cobra command tree in place: descriptions, flags, group titles, templates, the built-in help and completion commands, and Cobra’s errors. Call it right before root.Execute(). It never panics: a failure leaves the tree, or the part of it not yet translated, in English. |
Init(catalogs fs.FS, opts ...Option) string |
Detects the language and loads the matching catalog for the helpers below. Returns the language, or "" for English. Localize calls it for you. Calling it again switches catalogs for the helpers and the hooks; it never panics. |
T(s string) string |
The translation of s, or s unchanged. A format string (one with verbs) is looked up exactly, so call T before formatting; other text is translated like output. |
Sprintf(format string, args ...any) string |
fmt.Sprintf with a translated format. |
Errorf(format string, args ...any) error |
fmt.Errorf with a translated format. %w still wraps. |
Error(err error) string |
An error message translated for display. CLI-authored parts of a wrapped chain are translated, and server text is left as it is. "" for a nil error. |
Translate(s string, mode Mode) string |
Already formatted text translated in the given mode: ModeOutput for general output (it never splits label: rest, which could be data), ModeHelp for help text, ModeError for error messages, including wrapped-error chains. It is what Writer and Error use. |
Writer(w io.Writer) io.Writer |
A writer that translates CLI strings written to w, one Write at a time, in output mode. It returns w itself when output isn’t localized, exposes w’s Fd method for terminal detection, and writes the original bytes if the translation fails. |
WriterMode(w io.Writer, mode Mode) io.Writer |
Writer with an explicit mode: ModeHelp for a stream that carries help text, ModeError for one that carries error messages. The adapters for frameworks other than Cobra use it on the framework’s help and error writers. |
Lang() string |
The active language tag ("qps" for pseudo-localization), or "" for English. |
Reset() |
Undoes Init, for tests: the helpers become identity functions and the next Localize detects the language afresh. Command trees already localized keep their translated strings. |
Options
Section titled “Options”| Option | Description |
|---|---|
WithEnvVar(name) |
An application-specific override variable, such as YOURCLI_LANG, checked before LOCALIZER_LANG. |
WithLanguage(tag) |
Force a language, for example from a --lang flag. "en" or "off" disables localization. |
WithoutErrWriter() |
Don’t wrap the root command’s error writer or translate its error prefix. Cobra’s own error messages then stay in English; help is still translated, and Error still works. |
By default Localize translates the root command’s error prefix (Error:) in place when the catalog has
it, and replaces the root’s error writer — the one set with SetErr, or os.Stderr — with a wrapper that
translates Cobra’s error messages in error mode. The wrapper exposes the underlying writer’s Fd method, so
terminal detection keeps working, but it isn’t an *os.File: an application that type-asserts
cmd.ErrOrStderr() to *os.File needs WithoutErrWriter. Set your own error writer before calling
Localize; one set afterwards replaces the wrapper, and Cobra’s messages then print in English behind the
already translated prefix.
pip install localizer # import name: localizerPython 3.10 or later, no dependencies. It hooks Click 8.1 and later, Typer 0.17 and later (including the copy of Click that Typer 0.26+ bundles: its help, its errors, the prompt text and Click’s own prompt messages), rich-click 1.9 and later (its help panels, table labels and error panels) and the standard library’s argparse; the frameworks are optional. It makes no network calls, and it has no telemetry or credentials.
Functions
Section titled “Functions”| Function | Description |
|---|---|
localize(app, locales, *, env_var=None, language=None, without_error_hook=False, without_prompt_hook=False) -> str |
Localizes a Typer app, a Click command or an argparse parser: help, the framework’s own messages, the errors it prints, prompts. locales is a package name ("yourcli.locales"), a directory or a Traversable. Call it right before the app runs. Returns the language, or "" for English. Never raises. |
init(locales, *, env_var=None, language=None) -> str |
Detects the language and loads the matching catalog for the helpers below, without installing hooks. |
t(s: str) -> str |
The translation of s, or s unchanged. A format string is looked up exactly; formatted text is matched against the catalog’s templates. |
tf(fmt: str, *args, **kwargs) -> str |
str.format with a translated format string; falls back to the English format if the translation can’t be formatted. |
error(exc) -> str |
An exception’s message (format_message() or str()) translated for display. |
translate(s: str, mode=Mode.OUTPUT) -> str |
Translates already formatted text; Mode.HELP and Mode.ERROR allow splitting composite text into paragraphs and label: message pairs. |
lang() -> str |
The active language tag ("qps" for pseudo-localization), or "" for English. |
uninstall() |
Removes the hooks and forgets the language (for tests). |
Options
Section titled “Options”| Option | Description |
|---|---|
env_var="YOURCLI_LANG" |
An application-specific override variable (or a list of them), checked before LOCALIZER_LANG. |
language="de" |
Force a language, for example from a --lang option. "en" or "off" disables localization. |
without_error_hook=True |
Don’t hook the display of Click/Typer exceptions; the frameworks’ errors then stay in English. |
without_prompt_hook=True |
Don’t translate prompt/confirm texts. |
Environment variables
Section titled “Environment variables”The same in both runtimes:
| Variable | Effect |
|---|---|
LOCALIZER_LANG=ja |
Force a language. A list such as ja:en is allowed. |
LOCALIZER_LANG=en or off |
Disable localization. |
LOCALIZER_LANG=qps |
Pseudo-localization: every known string is shown as ⟦Ŝţŕîñĝ⟧, so strings that don’t go through Localizer stand out. |
LOCALIZER_DEBUG=1 |
Report on stderr each help string that has no translation, as it renders (localizer: untranslated (ja): "Add a task."), and internal failures that were swallowed, such as a catalog that fails to load or a hook that failed. Misses in output and error messages aren’t reported. |
LOCALIZER_DUMP=<file> |
Write every help string in the command tree as JSON, with hit or miss (see Testing). Both runtimes create the file new (an existing file is never overwritten) and ignore the variable in a root or setuid process. |
Language selection
Section titled “Language selection”Localizer uses the first of these that is set:
- the language passed with
WithLanguage/language=; - your application’s override variable (
WithEnvVar/env_var=), thenLOCALIZER_LANG. Besides a language or a list (ja:en), the value can beoff(alsonone,0,false,no,disable,disabled) orqps(alsoqps-ploc,pseudo); LC_ALL,LC_MESSAGESorLANG, in that order: the first one with a value decides. ACorPOSIXlocale means English. Otherwise GNULANGUAGE, if set, lists preferred languages ahead of that locale;LANGUAGEalone, when none of those three has a value;- the OS setting. On macOS the preferred languages (
AppleLanguages), read straight from~/Library/Preferences/.GlobalPreferences.plist— a file of at most 8 MiB, parsed without runningdefaults; on Windows the display languages; nothing on other systems; - English.
C and POSIX locales mean English, so scripts that set LC_ALL=C get stable output. Locale names are
normalized to BCP 47 (pt_BR.UTF-8 becomes pt-BR; zh_TW becomes zh-TW, which matches a zh-Hant
catalog but never zh-Hans) and matched to your catalogs. Only confident matches are used. Both runtimes
implement the same detection and matching rules and are tested against the same cases.
Output encoding (Python)
Section titled “Output encoding (Python)”Before a language is used, the Python runtime checks that sys.stdout and sys.stderr can encode the
catalog’s text. When one of them can’t, output stays in English, and LOCALIZER_DEBUG=1 says why
(localizer: stdout (cp1252) cannot encode the ja catalog; output stays in English). This is the situation
on Windows when output goes to a file or a pipe: Python then encodes with the ANSI code page (cp1252,
cp932, …), and a translated help screen would otherwise end in UnicodeEncodeError, or in \uXXXX
escapes where the stream’s error handler allows it. Output to the console itself, including Windows
Terminal, is UTF-8 and unaffected. To get translations through pipes and files as well, run Python in UTF-8
mode: set PYTHONUTF8=1 (or PYTHONIOENCODING=utf-8) in the environment. UTF-8 and UTF-16/32 streams
skip the check; for any other encoding the catalog is encoded once, a fraction of a millisecond.
© 2026 Snizyx Software LLC