Python 3.8+gettextfunction
gettext.pgettext()
contextual translation
Translates a string with a context — for when one English word must be translated differently in different parts of the interface.
Syntax
text = gettext.pgettext(context, message, /)
The word 'Open' on a button and in a file status translates differently ('Открыть' and 'Открыт'), while gettext() returns the same text for one key. The context becomes part of the key: the .mo stores it as 'context\x04string', so plain gettext cannot find such a translation. With no translation you get the string itself, without the context.
Examples
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({'button\x04Open': 'Открыть', 'status\x04Open': 'Открыт'}))
os.environ['LANGUAGE'] = 'ru'
gettext.bindtextdomain('app', 'loc')
gettext.textdomain('app')
print(gettext.pgettext('button', 'Open'), gettext.pgettext('status', 'Open')) # → Открыть Открыт
print(gettext.gettext('Open')) # → Open
See also
Open in the full glossarydocs.python.orgReport an inaccuracy