Python’s gettext module provides GNU gettext-style message translation for internationalizing Python apps. import gettext. translation: t = gettext.translation("myapp", localedir="locales", languages=["de"]) → GNUTranslations; t.gettext("Hello") → translated string. install: t.install() installs _() into builtins. bindtextdomain: gettext.bindtextdomain("myapp", "locales/") — sets locale dir. textdomain: gettext.textdomain("myapp") — active domain. find: gettext.find("myapp", "locales/", languages=["fr"]) → path to .mo or None. GNUTranslations: t.gettext(msg), t.ngettext(singular, plural, n), t.pgettext(context, msg), t.npgettext(context, singular, plural, n). NullTranslations: fallback that returns the msgid unchanged — t = gettext.NullTranslations(). Plural forms: ngettext("1 item", "{} items", n).format(n) — catalog defines plural formula per language. fallback=True in translation() returns NullTranslations instead of raising FileNotFoundError. languages=None uses LANGUAGE / LC_ALL / LC_MESSAGES / LANG env vars. codeset deprecated in 3.8+ (always UTF-8). Claude Code generates i18n wrappers, per-domain translator factories, catalog loaders, and pluralization helpers.
CLAUDE.md for gettext
## gettext Stack
- Stdlib: import gettext
- Load: t = gettext.translation("app", localedir="locales", languages=["fr"], fallback=True)
- Use: _ = t.gettext; _("Hello")
- Plural: t.ngettext("1 item", "{n} items", n).format(n=n)
- Context: t.pgettext("menu", "File")
- Fallback: t = gettext.NullTranslations() # no translation, returns msgid
gettext Translation Pipeline
# app/i18nutil.py — load, plural, context, fallback, domain registry, catalog inspect
from __future__ import annotations
import gettext
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable
# ─────────────────────────────────────────────────────────────────────────────
# 1. Translator factory and registry
# ─────────────────────────────────────────────────────────────────────────────
@dataclass
class Translator:
"""
Thin wrapper around GNUTranslations / NullTranslations.
Exposes gettext / ngettext / pgettext / npgettext with a uniform API.
Example:
t = Translator.load("myapp", "locales/", "de")
print(t._("Hello"))
print(t.ngettext("1 file", "{n} files", 3).format(n=3))
"""
_t: gettext.NullTranslations
language: str
@classmethod
def load(
cls,
domain: str,
localedir: str | Path,
language: str,
fallback: bool = True,
) -> "Translator":
"""
Load a compiled .mo catalog for domain + language.
Falls back to no-op NullTranslations if catalog is missing and fallback=True.
Example:
t = Translator.load("myapp", "locales/", "fr")
"""
t = gettext.translation(
domain,
localedir=str(localedir),
languages=[language],
fallback=fallback,
)
return cls(_t=t, language=language)
@classmethod
def null(cls, language: str = "en") -> "Translator":
"""Return a no-op translator (returns msgid unchanged)."""
return cls(_t=gettext.NullTranslations(), language=language)
def _(self, msg: str) -> str:
"""Translate a message string."""
return self._t.gettext(msg)
def ngettext(self, singular: str, plural: str, n: int) -> str:
"""Plural-aware translation."""
return self._t.ngettext(singular, plural, n)
def pgettext(self, context: str, msg: str) -> str:
"""Context-disambiguated translation."""
return self._t.pgettext(context, msg)
def npgettext(self, context: str, singular: str, plural: str, n: int) -> str:
"""Plural + context translation."""
return self._t.npgettext(context, singular, plural, n)
def n(self, singular: str, plural: str, count: int, **fmt) -> str:
"""
Translate with plural and format in one call.
Uses {count} as the interpolation key plus any extra **fmt kwargs.
Example:
t.n("1 item deleted", "{count} items deleted", 5)
"""
template = self.ngettext(singular, plural, count)
return template.format(count=count, **fmt)
class TranslatorRegistry:
"""
Cache of Translator instances keyed by (domain, language).
Avoids reloading .mo files on every request.
Example:
reg = TranslatorRegistry("locales/")
t = reg.get("myapp", "fr")
print(t._("Save"))
"""
def __init__(self, localedir: str | Path, fallback: bool = True) -> None:
self._localedir = Path(localedir)
self._fallback = fallback
self._cache: dict[tuple[str, str], Translator] = {}
def get(self, domain: str, language: str) -> Translator:
key = (domain, language)
if key not in self._cache:
self._cache[key] = Translator.load(
domain, self._localedir, language, fallback=self._fallback
)
return self._cache[key]
def clear(self) -> None:
self._cache.clear()
# ─────────────────────────────────────────────────────────────────────────────
# 2. Language detection helpers
# ─────────────────────────────────────────────────────────────────────────────
_ENV_VARS = ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG")
def detect_language(fallback: str = "en") -> str:
"""
Detect the user's preferred language from environment variables.
Returns the primary language tag (e.g. "de" from "de_DE.UTF-8").
Example:
lang = detect_language() # e.g. "en"
"""
for var in _ENV_VARS:
val = os.environ.get(var, "")
if val and val not in ("C", "POSIX", ""):
return val.split("_")[0].split(".")[0]
return fallback
def negotiate_language(
requested: list[str],
available: list[str],
fallback: str = "en",
) -> str:
"""
Select the best available language from a list of requested languages.
Tries exact match, then language-only prefix (e.g. "de" for "de-AT").
Example:
negotiate_language(["fr-CA", "fr", "en"], ["de", "fr", "en"])
# → "fr"
"""
available_set = set(available)
for lang in requested:
if lang in available_set:
return lang
prefix = lang.split("-")[0].split("_")[0]
if prefix in available_set:
return prefix
return fallback
# ─────────────────────────────────────────────────────────────────────────────
# 3. Catalog discovery and inspection
# ─────────────────────────────────────────────────────────────────────────────
@dataclass
class CatalogInfo:
domain: str
language: str
path: Path
size: int
def __str__(self) -> str:
return f"{self.domain}/{self.language} {self.size:,d} B {self.path}"
def find_catalogs(localedir: str | Path, domain: str | None = None) -> list[CatalogInfo]:
"""
Discover all compiled .mo files under localedir.
Optional domain filter.
Example:
for c in find_catalogs("locales/"):
print(c)
"""
root = Path(localedir)
results: list[CatalogInfo] = []
# Standard layout: locales/<lang>/LC_MESSAGES/<domain>.mo
for mo_path in sorted(root.glob("*/LC_MESSAGES/*.mo")):
lang = mo_path.parts[-3]
dom = mo_path.stem
if domain and dom != domain:
continue
results.append(CatalogInfo(
domain=dom, language=lang,
path=mo_path, size=mo_path.stat().st_size,
))
return results
def available_languages(localedir: str | Path, domain: str) -> list[str]:
"""
Return sorted list of language codes that have a compiled catalog for domain.
Example:
langs = available_languages("locales/", "myapp")
# e.g. ["de", "es", "fr", "ja"]
"""
return sorted({c.language for c in find_catalogs(localedir, domain)})
# ─────────────────────────────────────────────────────────────────────────────
# 4. Lazy translation (deferred _() for module-level strings)
# ─────────────────────────────────────────────────────────────────────────────
class LazyTranslation:
"""
Placeholder for a translatable string that is resolved at render time.
Use at module level where the language is not yet known.
Example:
GREETING = LazyTranslation("Hello")
...
print(GREETING.resolve(translator))
"""
def __init__(self, msgid: str, context: str | None = None) -> None:
self.msgid = msgid
self.context = context
def resolve(self, t: Translator) -> str:
if self.context:
return t.pgettext(self.context, self.msgid)
return t._(self.msgid)
def __repr__(self) -> str:
return f"LazyTranslation({self.msgid!r})"
def lazy_(msgid: str, context: str | None = None) -> LazyTranslation:
"""
Create a lazy translatable string for module-level use.
Example:
ERROR_LABEL = lazy_("Error")
SAVE_LABEL = lazy_("Save", context="button")
"""
return LazyTranslation(msgid, context)
# ─────────────────────────────────────────────────────────────────────────────
# 5. .pot template writer (for tooling)
# ─────────────────────────────────────────────────────────────────────────────
def write_pot_header(
domain: str,
version: str = "1.0",
charset: str = "UTF-8",
) -> str:
"""
Generate a minimal .pot file header string for a translation domain.
Useful when programmatically building message catalogs for small projects.
Example:
pot = write_pot_header("myapp", version="2.1")
print(pot)
"""
return (
f'# Translation template for {domain}\n'
f'msgid ""\n'
f'msgstr ""\n'
f'"Project-Id-Version: {domain} {version}\\n"\n'
f'"MIME-Version: 1.0\\n"\n'
f'"Content-Type: text/plain; charset={charset}\\n"\n'
f'"Content-Transfer-Encoding: 8bit\\n"\n'
f'"Plural-Forms: nplurals=2; plural=(n != 1);\\n"\n'
f'\n'
)
def write_pot_entries(messages: list[str | tuple[str, str]]) -> str:
"""
Generate .pot msgid entries from a list of strings or (context, msgid) tuples.
Example:
print(write_pot_entries(["Hello", ("button", "Save"), "Cancel"]))
"""
lines: list[str] = []
for msg in messages:
if isinstance(msg, tuple):
ctx, msgid = msg
lines.append(f'msgctxt "{ctx}"')
lines.append(f'msgid "{msgid}"')
else:
lines.append(f'msgid "{msg}"')
lines.append('msgstr ""')
lines.append("")
return "\n".join(lines)
# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
import tempfile, struct
print("=== gettext demo ===")
# ── build a minimal .mo file in memory ────────────────────────────────────
# .mo binary format: magic, revision, count, offsets for originals/translations
def _make_mo(pairs: list[tuple[bytes, bytes]]) -> bytes:
"""Build a minimal GNU .mo binary from msgid → msgstr pairs."""
MAGIC = 0x950412de
n = len(pairs)
# Offsets table starts after header (7 * 4 bytes)
orig_off = 7 * 4
trans_off = orig_off + n * 8
strings_off = trans_off + n * 8
orig_table = []
trans_table = []
strings = bytearray()
pos = strings_off
for msgid, msgstr in pairs:
orig_table.append((len(msgid), pos - strings_off))
strings.extend(msgid + b"\x00")
pos += len(msgid) + 1
for msgid, msgstr in pairs:
trans_table.append((len(msgstr), pos - strings_off))
strings.extend(msgstr + b"\x00")
pos += len(msgstr) + 1
header = struct.pack("<IIIIIII",
MAGIC, 0, n,
orig_off, trans_off,
0, 0,
)
orig_bytes = b"".join(struct.pack("<II", l, o + strings_off) for l, o in orig_table)
trans_bytes = b"".join(struct.pack("<II", l, o + strings_off) for l, o in trans_table)
return header + orig_bytes + trans_bytes + bytes(strings)
# ── build catalogs for "de" and "fr" ──────────────────────────────────────
with tempfile.TemporaryDirectory() as tmpdir:
locales = Path(tmpdir) / "locales"
for lang, pairs in [
("de", [
(b"", b"Content-Type: text/plain; charset=UTF-8\nPlural-Forms: nplurals=2; plural=(n != 1);\n"),
(b"Hello", b"Hallo"),
(b"Save", b"Speichern"),
(b"Cancel", b"Abbrechen"),
(b"1 item\x001 items", b"1 Artikel\x00%d Artikel"),
]),
("fr", [
(b"", b"Content-Type: text/plain; charset=UTF-8\nPlural-Forms: nplurals=2; plural=(n > 1);\n"),
(b"Hello", b"Bonjour"),
(b"Save", b"Enregistrer"),
(b"Cancel", b"Annuler"),
(b"1 item\x001 items", b"1 article\x00%d articles"),
]),
]:
mo_dir = locales / lang / "LC_MESSAGES"
mo_dir.mkdir(parents=True)
(mo_dir / "demo.mo").write_bytes(_make_mo(pairs))
# ── load and use Translator ────────────────────────────────────────────
print("\n--- Translator.load ---")
registry = TranslatorRegistry(locales)
for lang in ("de", "fr", "en"):
t = registry.get("demo", lang)
print(f" [{lang}] Hello → {t._('Hello')!r}")
print(f" [{lang}] Save → {t._('Save')!r}")
# ── plural forms ───────────────────────────────────────────────────────
print("\n--- ngettext / n() ---")
for lang in ("de", "fr"):
t = registry.get("demo", lang)
for n in (1, 3):
raw = t.ngettext("1 item", "1 items", n)
print(f" [{lang}] n={n}: {raw!r}")
# ── NullTranslations fallback ──────────────────────────────────────────
print("\n--- NullTranslations fallback ---")
t_null = Translator.null("en")
print(f" _ ('Hello') → {t_null._('Hello')!r}")
# ── LazyTranslation ────────────────────────────────────────────────────
print("\n--- LazyTranslation ---")
GREETING = lazy_("Hello")
t_de = registry.get("demo", "de")
print(f" lazy resolved [de]: {GREETING.resolve(t_de)!r}")
# ── language negotiation ───────────────────────────────────────────────
print("\n--- negotiate_language ---")
available = available_languages(locales, "demo")
print(f" available: {available}")
for req in [["fr-CA", "en"], ["de-AT", "en"], ["ja", "zh", "en"]]:
best = negotiate_language(req, available)
print(f" {req} → {best!r}")
# ── find_catalogs ──────────────────────────────────────────────────────
print("\n--- find_catalogs ---")
for c in find_catalogs(locales, "demo"):
print(f" {c}")
# ── pot header ────────────────────────────────────────────────────────
print("\n--- write_pot_header ---")
print(write_pot_header("myapp", "1.0").rstrip())
print("\n=== done ===")
For the babel alternative — Babel (PyPI) provides a comprehensive i18n framework: it extracts _() calls from source code (pybabel extract), compiles .pot → .po → .mo with proper plural forms for 100+ languages, handles date/number/currency formatting per locale, and integrates with Jinja2 and Flask — use Babel for production applications where you need the full translation workflow; use gettext directly when you only need to load compiled .mo catalogs at runtime without the extraction/compilation toolchain, or when adding i18n to a lightweight script or CLI. For the fluent-runtime alternative — fluent-runtime (PyPI) implements Mozilla’s Fluent localization system, which separates translation logic from code more completely than GNU gettext by encoding grammatical rules (plurals, genders, inflections) inside the .ftl message files themselves rather than in the calling code — use fluent-runtime when your application has complex grammatical variation requirements or when building multilingual Mozilla-ecosystem tooling; use gettext when your project follows GNU/Linux conventions, when your translators already use .po/.mo workflows with tools like Poedit or Weblate, or when you need POSIX command-line tool compatibility. The Claude Skills 360 bundle includes gettext skill sets covering Translator wrapper with _()/ngettext()/pgettext()/npgettext()/n(), TranslatorRegistry caching factory, detect_language()/negotiate_language() Accept-Language helpers, CatalogInfo with find_catalogs()/available_languages() discovery, LazyTranslation/lazy_() deferred strings, and write_pot_header()/write_pot_entries() template builders. Start with the free tier to try i18n translation patterns and gettext pipeline code generation.