On this page
  1. gettext
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Class-Based vs. Global (install()) Translation
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

gettext

Prev: getpass | Up: stdlib_module | Next: glob
Rel: wave, colorsys, locale, turtle, turtledemo
Ref: docs.python.org — gettext
Tags: #public #python3 #stdlib


Import

import gettext

Overview

GNU gettext internationalization (i18n) and localization (l10n) API for translating user-facing strings using .po/.mo message catalogs (translation(), GNUTranslations, NullTranslations). Use gettext to separate translatable UI text from code and handle language-specific plural rules cleanly.

Quick Start

import gettext

# Fallback NullTranslations passes strings through unchanged when no .mo catalog exists
t = gettext.translation("myapp", localedir="locale", languages=["fr"], fallback=True)
_ = t.gettext
ngettext = t.ngettext

assert _("Hello") == "Hello"
assert ngettext("%d file", "%d files", 2) % 2 == "2 files"

Implementation Walkthrough

1. Class-Based vs. Global (install()) Translation

Prefer the class-based API (t = gettext.translation(...)) over gettext.install()—it avoids mutating builtins._ and lets web servers or multi-tenant apps serve different languages per request:

import gettext
from pathlib import Path

def get_translator(locale_dir: Path, lang: str) -> gettext.NullTranslations:
    return gettext.translation(
        domain="messages",
        localedir=str(locale_dir),
        languages=[lang],
        fallback=True,
    )

# Standard workflow:
# 1. Extract strings with xgettext / pybabel into messages.pot -> <lang>/LC_MESSAGES/messages.po
# 2. Compile .po -> .mo with msgfmt
# 3. Load via get_translator(Path("locale"), "es").gettext("Save")

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes