Python Glossary Русский

all Python 3gettextfunction

gettext.translation()

translation catalogs

Finds and loads the translation catalog for a domain and languages. The main way to get an object with gettext and ngettext methods.

Syntax

t = gettext.translation(domain, localedir=None, languages=None, class_=None, fallback=False)

Without fallback=True a missing .mo file means FileNotFoundError, and the program crashes for a user with an unexpected locale. With fallback=True you get NullTranslations, which returns the original strings. Loaded catalogs are cached by file path, so editing the .mo while the program runs has no effect. The old name Catalog is the same object as translation; write translation() in new code.

Examples

import gettext
try:
    gettext.translation('app', localedir='loc', languages=['ru'])
except FileNotFoundError as e:
    print(type(e).__name__)  # → FileNotFoundError
t = gettext.translation('app', 'loc', ['ru'], fallback=True)
print(t.gettext('Hello'))  # → Hello
import io, struct
def mo(cat):  # собрать каталог .mo в памяти
    cat = {'': 'Content-Type: text/plain; charset=UTF-8\n', **cat}
    ks = sorted(cat)
    bs = [k.encode() for k in ks] + [cat[k].encode() for k in ks]
    n, data, tab = len(ks), b'', b''
    for b in bs:
        tab += struct.pack('<2I', len(b), 28 + 16 * n + len(data))
        data += b + b'\0'
    return struct.pack('<7I', 0x950412de, 0, n, 28, 28 + 8 * n, 0, 0) + tab + data
import gettext
import os
os.makedirs('loc/ru/LC_MESSAGES', exist_ok=True)
open('loc/ru/LC_MESSAGES/app.mo', 'wb').write(mo({'Hello': 'Привет'}))
_ = gettext.translation('app', 'loc', ['ru']).gettext
print(_('Hello'), _('Bye'))  # → Привет Bye

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy