Select Message Catalogs with gettext
Core idea
gettext separates message identifiers from translated strings. gettext.translation(domain, localedir=..., languages=[...]) loads compiled GNU .mo catalogs from language-specific LC_MESSAGES directories. Use the returned object locally; fallback=True returns a NullTranslations object when no catalog is found. ngettext selects a singular or plural message using catalog rules or the default fallback.
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) import gettext t = gettext.translation("demo", localedir=root, languages=["fa"], fallback=True) print(t.gettext("Ready")) print(type(t).__name__)The deliberately empty directory has no Persian catalog, so the source message is returned; fallback does not translate.
Keep plural selection separate
import gettextt = gettext.NullTranslations()for count in (1, 3): message = t.ngettext("{n} item", "{n} items", count) print(message.format(n=count))Select the message first, then interpolate the value using a stable placeholder. A real translation catalog can define different plural rules.
Common mistake
Do not concatenate fragments assuming all languages use the same word order. Do not install a global translation for every request. Test real catalogs, placeholder parity, plural rules and RTL rendering separately. The examples intentionally test fallback, not an installed Persian catalog.
Practice
With a trusted compiled demo.mo catalog available, place it at fa/LC_MESSAGES/demo.mo under a private localedir. Load languages=["fa"] with fallback=False, compare a known translation against the source text, and test a missing message. If no catalog is available, repeat the missing-catalog example instead.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Gettext message selection
Check your understanding of gettext localization.
What is printed?
import gettextprint(gettext.NullTranslations().gettext("Ready"))What is printed?
import gettextprint(gettext.NullTranslations().ngettext("one","many",2))What does fallback=True do when no catalog exists?
Where is a compiled catalog for domain demo and language fa conventionally located?