Claude Code for gettext: Python Internationalization and Translation — Claude Skills 360 Blog
Blog / AI / Claude Code for gettext: Python Internationalization and Translation
AI

Claude Code for gettext: Python Internationalization and Translation

Published: September 22, 2028
Read time: 5 min read
By: Claude Skills 360

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.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free