gettext.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. """Internationalization and localization support.
  2. This module provides internationalization (I18N) and localization (L10N)
  3. support for your Python programs by providing an interface to the GNU gettext
  4. message catalog library.
  5. I18N refers to the operation by which a program is made aware of multiple
  6. languages. L10N refers to the adaptation of your program, once
  7. internationalized, to the local language and cultural habits.
  8. """
  9. # This module represents the integration of work, contributions, feedback, and
  10. # suggestions from the following people:
  11. #
  12. # Martin von Loewis, who wrote the initial implementation of the underlying
  13. # C-based libintlmodule (later renamed _gettext), along with a skeletal
  14. # gettext.py implementation.
  15. #
  16. # Peter Funk, who wrote fintl.py, a fairly complete wrapper around intlmodule,
  17. # which also included a pure-Python implementation to read .mo files if
  18. # intlmodule wasn't available.
  19. #
  20. # James Henstridge, who also wrote a gettext.py module, which has some
  21. # interesting, but currently unsupported experimental features: the notion of
  22. # a Catalog class and instances, and the ability to add to a catalog file via
  23. # a Python API.
  24. #
  25. # Barry Warsaw integrated these modules, wrote the .install() API and code,
  26. # and conformed all C and Python code to Python's coding standards.
  27. #
  28. # Francois Pinard and Marc-Andre Lemburg also contributed valuably to this
  29. # module.
  30. #
  31. # J. David Ibanez implemented plural forms. Bruno Haible fixed some bugs.
  32. #
  33. # TODO:
  34. # - Lazy loading of .mo files. Currently the entire catalog is loaded into
  35. # memory, but that's probably bad for large translated programs. Instead,
  36. # the lexical sort of original strings in GNU .mo files should be exploited
  37. # to do binary searches and lazy initializations. Or you might want to use
  38. # the undocumented double-hash algorithm for .mo files with hash tables, but
  39. # you'll need to study the GNU gettext code to do this.
  40. #
  41. # - Support Solaris .mo file formats. Unfortunately, we've been unable to
  42. # find this format documented anywhere.
  43. import locale
  44. import os
  45. import re
  46. import sys
  47. __all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
  48. 'find', 'translation', 'install', 'textdomain', 'bindtextdomain',
  49. 'bind_textdomain_codeset',
  50. 'dgettext', 'dngettext', 'gettext', 'lgettext', 'ldgettext',
  51. 'ldngettext', 'lngettext', 'ngettext',
  52. 'pgettext', 'dpgettext', 'npgettext', 'dnpgettext',
  53. ]
  54. _default_localedir = os.path.join(sys.base_prefix, 'share', 'locale')
  55. # Expression parsing for plural form selection.
  56. #
  57. # The gettext library supports a small subset of C syntax. The only
  58. # incompatible difference is that integer literals starting with zero are
  59. # decimal.
  60. #
  61. # https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms
  62. # http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-runtime/intl/plural.y
  63. _token_pattern = re.compile(r"""
  64. (?P<WHITESPACES>[ \t]+) | # spaces and horizontal tabs
  65. (?P<NUMBER>[0-9]+\b) | # decimal integer
  66. (?P<NAME>n\b) | # only n is allowed
  67. (?P<PARENTHESIS>[()]) |
  68. (?P<OPERATOR>[-*/%+?:]|[><!]=?|==|&&|\|\|) | # !, *, /, %, +, -, <, >,
  69. # <=, >=, ==, !=, &&, ||,
  70. # ? :
  71. # unary and bitwise ops
  72. # not allowed
  73. (?P<INVALID>\w+|.) # invalid token
  74. """, re.VERBOSE|re.DOTALL)
  75. def _tokenize(plural):
  76. for mo in re.finditer(_token_pattern, plural):
  77. kind = mo.lastgroup
  78. if kind == 'WHITESPACES':
  79. continue
  80. value = mo.group(kind)
  81. if kind == 'INVALID':
  82. raise ValueError('invalid token in plural form: %s' % value)
  83. yield value
  84. yield ''
  85. def _error(value):
  86. if value:
  87. return ValueError('unexpected token in plural form: %s' % value)
  88. else:
  89. return ValueError('unexpected end of plural form')
  90. _binary_ops = (
  91. ('||',),
  92. ('&&',),
  93. ('==', '!='),
  94. ('<', '>', '<=', '>='),
  95. ('+', '-'),
  96. ('*', '/', '%'),
  97. )
  98. _binary_ops = {op: i for i, ops in enumerate(_binary_ops, 1) for op in ops}
  99. _c2py_ops = {'||': 'or', '&&': 'and', '/': '//'}
  100. def _parse(tokens, priority=-1):
  101. result = ''
  102. nexttok = next(tokens)
  103. while nexttok == '!':
  104. result += 'not '
  105. nexttok = next(tokens)
  106. if nexttok == '(':
  107. sub, nexttok = _parse(tokens)
  108. result = '%s(%s)' % (result, sub)
  109. if nexttok != ')':
  110. raise ValueError('unbalanced parenthesis in plural form')
  111. elif nexttok == 'n':
  112. result = '%s%s' % (result, nexttok)
  113. else:
  114. try:
  115. value = int(nexttok, 10)
  116. except ValueError:
  117. raise _error(nexttok) from None
  118. result = '%s%d' % (result, value)
  119. nexttok = next(tokens)
  120. j = 100
  121. while nexttok in _binary_ops:
  122. i = _binary_ops[nexttok]
  123. if i < priority:
  124. break
  125. # Break chained comparisons
  126. if i in (3, 4) and j in (3, 4): # '==', '!=', '<', '>', '<=', '>='
  127. result = '(%s)' % result
  128. # Replace some C operators by their Python equivalents
  129. op = _c2py_ops.get(nexttok, nexttok)
  130. right, nexttok = _parse(tokens, i + 1)
  131. result = '%s %s %s' % (result, op, right)
  132. j = i
  133. if j == priority == 4: # '<', '>', '<=', '>='
  134. result = '(%s)' % result
  135. if nexttok == '?' and priority <= 0:
  136. if_true, nexttok = _parse(tokens, 0)
  137. if nexttok != ':':
  138. raise _error(nexttok)
  139. if_false, nexttok = _parse(tokens)
  140. result = '%s if %s else %s' % (if_true, result, if_false)
  141. if priority == 0:
  142. result = '(%s)' % result
  143. return result, nexttok
  144. def _as_int(n):
  145. try:
  146. i = round(n)
  147. except TypeError:
  148. raise TypeError('Plural value must be an integer, got %s' %
  149. (n.__class__.__name__,)) from None
  150. import warnings
  151. warnings.warn('Plural value must be an integer, got %s' %
  152. (n.__class__.__name__,),
  153. DeprecationWarning, 4)
  154. return n
  155. def c2py(plural):
  156. """Gets a C expression as used in PO files for plural forms and returns a
  157. Python function that implements an equivalent expression.
  158. """
  159. if len(plural) > 1000:
  160. raise ValueError('plural form expression is too long')
  161. try:
  162. result, nexttok = _parse(_tokenize(plural))
  163. if nexttok:
  164. raise _error(nexttok)
  165. depth = 0
  166. for c in result:
  167. if c == '(':
  168. depth += 1
  169. if depth > 20:
  170. # Python compiler limit is about 90.
  171. # The most complex example has 2.
  172. raise ValueError('plural form expression is too complex')
  173. elif c == ')':
  174. depth -= 1
  175. ns = {'_as_int': _as_int}
  176. exec('''if True:
  177. def func(n):
  178. if not isinstance(n, int):
  179. n = _as_int(n)
  180. return int(%s)
  181. ''' % result, ns)
  182. return ns['func']
  183. except RecursionError:
  184. # Recursion error can be raised in _parse() or exec().
  185. raise ValueError('plural form expression is too complex')
  186. def _expand_lang(loc):
  187. loc = locale.normalize(loc)
  188. COMPONENT_CODESET = 1 << 0
  189. COMPONENT_TERRITORY = 1 << 1
  190. COMPONENT_MODIFIER = 1 << 2
  191. # split up the locale into its base components
  192. mask = 0
  193. pos = loc.find('@')
  194. if pos >= 0:
  195. modifier = loc[pos:]
  196. loc = loc[:pos]
  197. mask |= COMPONENT_MODIFIER
  198. else:
  199. modifier = ''
  200. pos = loc.find('.')
  201. if pos >= 0:
  202. codeset = loc[pos:]
  203. loc = loc[:pos]
  204. mask |= COMPONENT_CODESET
  205. else:
  206. codeset = ''
  207. pos = loc.find('_')
  208. if pos >= 0:
  209. territory = loc[pos:]
  210. loc = loc[:pos]
  211. mask |= COMPONENT_TERRITORY
  212. else:
  213. territory = ''
  214. language = loc
  215. ret = []
  216. for i in range(mask+1):
  217. if not (i & ~mask): # if all components for this combo exist ...
  218. val = language
  219. if i & COMPONENT_TERRITORY: val += territory
  220. if i & COMPONENT_CODESET: val += codeset
  221. if i & COMPONENT_MODIFIER: val += modifier
  222. ret.append(val)
  223. ret.reverse()
  224. return ret
  225. class NullTranslations:
  226. def __init__(self, fp=None):
  227. self._info = {}
  228. self._charset = None
  229. self._output_charset = None
  230. self._fallback = None
  231. if fp is not None:
  232. self._parse(fp)
  233. def _parse(self, fp):
  234. pass
  235. def add_fallback(self, fallback):
  236. if self._fallback:
  237. self._fallback.add_fallback(fallback)
  238. else:
  239. self._fallback = fallback
  240. def gettext(self, message):
  241. if self._fallback:
  242. return self._fallback.gettext(message)
  243. return message
  244. def lgettext(self, message):
  245. import warnings
  246. warnings.warn('lgettext() is deprecated, use gettext() instead',
  247. DeprecationWarning, 2)
  248. if self._fallback:
  249. with warnings.catch_warnings():
  250. warnings.filterwarnings('ignore', r'.*\blgettext\b.*',
  251. DeprecationWarning)
  252. return self._fallback.lgettext(message)
  253. if self._output_charset:
  254. return message.encode(self._output_charset)
  255. return message.encode(locale.getpreferredencoding())
  256. def ngettext(self, msgid1, msgid2, n):
  257. if self._fallback:
  258. return self._fallback.ngettext(msgid1, msgid2, n)
  259. if n == 1:
  260. return msgid1
  261. else:
  262. return msgid2
  263. def lngettext(self, msgid1, msgid2, n):
  264. import warnings
  265. warnings.warn('lngettext() is deprecated, use ngettext() instead',
  266. DeprecationWarning, 2)
  267. if self._fallback:
  268. with warnings.catch_warnings():
  269. warnings.filterwarnings('ignore', r'.*\blngettext\b.*',
  270. DeprecationWarning)
  271. return self._fallback.lngettext(msgid1, msgid2, n)
  272. if n == 1:
  273. tmsg = msgid1
  274. else:
  275. tmsg = msgid2
  276. if self._output_charset:
  277. return tmsg.encode(self._output_charset)
  278. return tmsg.encode(locale.getpreferredencoding())
  279. def pgettext(self, context, message):
  280. if self._fallback:
  281. return self._fallback.pgettext(context, message)
  282. return message
  283. def npgettext(self, context, msgid1, msgid2, n):
  284. if self._fallback:
  285. return self._fallback.npgettext(context, msgid1, msgid2, n)
  286. if n == 1:
  287. return msgid1
  288. else:
  289. return msgid2
  290. def info(self):
  291. return self._info
  292. def charset(self):
  293. return self._charset
  294. def output_charset(self):
  295. import warnings
  296. warnings.warn('output_charset() is deprecated',
  297. DeprecationWarning, 2)
  298. return self._output_charset
  299. def set_output_charset(self, charset):
  300. import warnings
  301. warnings.warn('set_output_charset() is deprecated',
  302. DeprecationWarning, 2)
  303. self._output_charset = charset
  304. def install(self, names=None):
  305. import builtins
  306. builtins.__dict__['_'] = self.gettext
  307. if names is not None:
  308. allowed = {'gettext', 'lgettext', 'lngettext',
  309. 'ngettext', 'npgettext', 'pgettext'}
  310. for name in allowed & set(names):
  311. builtins.__dict__[name] = getattr(self, name)
  312. class GNUTranslations(NullTranslations):
  313. # Magic number of .mo files
  314. LE_MAGIC = 0x950412de
  315. BE_MAGIC = 0xde120495
  316. # The encoding of a msgctxt and a msgid in a .mo file is
  317. # msgctxt + "\x04" + msgid (gettext version >= 0.15)
  318. CONTEXT = "%s\x04%s"
  319. # Acceptable .mo versions
  320. VERSIONS = (0, 1)
  321. def _get_versions(self, version):
  322. """Returns a tuple of major version, minor version"""
  323. return (version >> 16, version & 0xffff)
  324. def _parse(self, fp):
  325. """Override this method to support alternative .mo formats."""
  326. # Delay struct import for speeding up gettext import when .mo files
  327. # are not used.
  328. from struct import unpack
  329. filename = getattr(fp, 'name', '')
  330. # Parse the .mo file header, which consists of 5 little endian 32
  331. # bit words.
  332. self._catalog = catalog = {}
  333. self.plural = lambda n: int(n != 1) # germanic plural by default
  334. buf = fp.read()
  335. buflen = len(buf)
  336. # Are we big endian or little endian?
  337. magic = unpack('<I', buf[:4])[0]
  338. if magic == self.LE_MAGIC:
  339. version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
  340. ii = '<II'
  341. elif magic == self.BE_MAGIC:
  342. version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
  343. ii = '>II'
  344. else:
  345. raise OSError(0, 'Bad magic number', filename)
  346. major_version, minor_version = self._get_versions(version)
  347. if major_version not in self.VERSIONS:
  348. raise OSError(0, 'Bad version number ' + str(major_version), filename)
  349. # Now put all messages from the .mo file buffer into the catalog
  350. # dictionary.
  351. for i in range(0, msgcount):
  352. mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
  353. mend = moff + mlen
  354. tlen, toff = unpack(ii, buf[transidx:transidx+8])
  355. tend = toff + tlen
  356. if mend < buflen and tend < buflen:
  357. msg = buf[moff:mend]
  358. tmsg = buf[toff:tend]
  359. else:
  360. raise OSError(0, 'File is corrupt', filename)
  361. # See if we're looking at GNU .mo conventions for metadata
  362. if mlen == 0:
  363. # Catalog description
  364. lastk = None
  365. for b_item in tmsg.split(b'\n'):
  366. item = b_item.decode().strip()
  367. if not item:
  368. continue
  369. # Skip over comment lines:
  370. if item.startswith('#-#-#-#-#') and item.endswith('#-#-#-#-#'):
  371. continue
  372. k = v = None
  373. if ':' in item:
  374. k, v = item.split(':', 1)
  375. k = k.strip().lower()
  376. v = v.strip()
  377. self._info[k] = v
  378. lastk = k
  379. elif lastk:
  380. self._info[lastk] += '\n' + item
  381. if k == 'content-type':
  382. self._charset = v.split('charset=')[1]
  383. elif k == 'plural-forms':
  384. v = v.split(';')
  385. plural = v[1].split('plural=')[1]
  386. self.plural = c2py(plural)
  387. # Note: we unconditionally convert both msgids and msgstrs to
  388. # Unicode using the character encoding specified in the charset
  389. # parameter of the Content-Type header. The gettext documentation
  390. # strongly encourages msgids to be us-ascii, but some applications
  391. # require alternative encodings (e.g. Zope's ZCML and ZPT). For
  392. # traditional gettext applications, the msgid conversion will
  393. # cause no problems since us-ascii should always be a subset of
  394. # the charset encoding. We may want to fall back to 8-bit msgids
  395. # if the Unicode conversion fails.
  396. charset = self._charset or 'ascii'
  397. if b'\x00' in msg:
  398. # Plural forms
  399. msgid1, msgid2 = msg.split(b'\x00')
  400. tmsg = tmsg.split(b'\x00')
  401. msgid1 = str(msgid1, charset)
  402. for i, x in enumerate(tmsg):
  403. catalog[(msgid1, i)] = str(x, charset)
  404. else:
  405. catalog[str(msg, charset)] = str(tmsg, charset)
  406. # advance to next entry in the seek tables
  407. masteridx += 8
  408. transidx += 8
  409. def lgettext(self, message):
  410. import warnings
  411. warnings.warn('lgettext() is deprecated, use gettext() instead',
  412. DeprecationWarning, 2)
  413. missing = object()
  414. tmsg = self._catalog.get(message, missing)
  415. if tmsg is missing:
  416. if self._fallback:
  417. return self._fallback.lgettext(message)
  418. tmsg = message
  419. if self._output_charset:
  420. return tmsg.encode(self._output_charset)
  421. return tmsg.encode(locale.getpreferredencoding())
  422. def lngettext(self, msgid1, msgid2, n):
  423. import warnings
  424. warnings.warn('lngettext() is deprecated, use ngettext() instead',
  425. DeprecationWarning, 2)
  426. try:
  427. tmsg = self._catalog[(msgid1, self.plural(n))]
  428. except KeyError:
  429. if self._fallback:
  430. return self._fallback.lngettext(msgid1, msgid2, n)
  431. if n == 1:
  432. tmsg = msgid1
  433. else:
  434. tmsg = msgid2
  435. if self._output_charset:
  436. return tmsg.encode(self._output_charset)
  437. return tmsg.encode(locale.getpreferredencoding())
  438. def gettext(self, message):
  439. missing = object()
  440. tmsg = self._catalog.get(message, missing)
  441. if tmsg is missing:
  442. if self._fallback:
  443. return self._fallback.gettext(message)
  444. return message
  445. return tmsg
  446. def ngettext(self, msgid1, msgid2, n):
  447. try:
  448. tmsg = self._catalog[(msgid1, self.plural(n))]
  449. except KeyError:
  450. if self._fallback:
  451. return self._fallback.ngettext(msgid1, msgid2, n)
  452. if n == 1:
  453. tmsg = msgid1
  454. else:
  455. tmsg = msgid2
  456. return tmsg
  457. def pgettext(self, context, message):
  458. ctxt_msg_id = self.CONTEXT % (context, message)
  459. missing = object()
  460. tmsg = self._catalog.get(ctxt_msg_id, missing)
  461. if tmsg is missing:
  462. if self._fallback:
  463. return self._fallback.pgettext(context, message)
  464. return message
  465. return tmsg
  466. def npgettext(self, context, msgid1, msgid2, n):
  467. ctxt_msg_id = self.CONTEXT % (context, msgid1)
  468. try:
  469. tmsg = self._catalog[ctxt_msg_id, self.plural(n)]
  470. except KeyError:
  471. if self._fallback:
  472. return self._fallback.npgettext(context, msgid1, msgid2, n)
  473. if n == 1:
  474. tmsg = msgid1
  475. else:
  476. tmsg = msgid2
  477. return tmsg
  478. # Locate a .mo file using the gettext strategy
  479. def find(domain, localedir=None, languages=None, all=False):
  480. # Get some reasonable defaults for arguments that were not supplied
  481. if localedir is None:
  482. localedir = _default_localedir
  483. if languages is None:
  484. languages = []
  485. for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
  486. val = os.environ.get(envar)
  487. if val:
  488. languages = val.split(':')
  489. break
  490. if 'C' not in languages:
  491. languages.append('C')
  492. # now normalize and expand the languages
  493. nelangs = []
  494. for lang in languages:
  495. for nelang in _expand_lang(lang):
  496. if nelang not in nelangs:
  497. nelangs.append(nelang)
  498. # select a language
  499. if all:
  500. result = []
  501. else:
  502. result = None
  503. for lang in nelangs:
  504. if lang == 'C':
  505. break
  506. mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
  507. if os.path.exists(mofile):
  508. if all:
  509. result.append(mofile)
  510. else:
  511. return mofile
  512. return result
  513. # a mapping between absolute .mo file path and Translation object
  514. _translations = {}
  515. _unspecified = ['unspecified']
  516. def translation(domain, localedir=None, languages=None,
  517. class_=None, fallback=False, codeset=_unspecified):
  518. if class_ is None:
  519. class_ = GNUTranslations
  520. mofiles = find(domain, localedir, languages, all=True)
  521. if not mofiles:
  522. if fallback:
  523. return NullTranslations()
  524. from errno import ENOENT
  525. raise FileNotFoundError(ENOENT,
  526. 'No translation file found for domain', domain)
  527. # Avoid opening, reading, and parsing the .mo file after it's been done
  528. # once.
  529. result = None
  530. for mofile in mofiles:
  531. key = (class_, os.path.abspath(mofile))
  532. t = _translations.get(key)
  533. if t is None:
  534. with open(mofile, 'rb') as fp:
  535. t = _translations.setdefault(key, class_(fp))
  536. # Copy the translation object to allow setting fallbacks and
  537. # output charset. All other instance data is shared with the
  538. # cached object.
  539. # Delay copy import for speeding up gettext import when .mo files
  540. # are not used.
  541. import copy
  542. t = copy.copy(t)
  543. if codeset is not _unspecified:
  544. import warnings
  545. warnings.warn('parameter codeset is deprecated',
  546. DeprecationWarning, 2)
  547. if codeset:
  548. with warnings.catch_warnings():
  549. warnings.filterwarnings('ignore', r'.*\bset_output_charset\b.*',
  550. DeprecationWarning)
  551. t.set_output_charset(codeset)
  552. if result is None:
  553. result = t
  554. else:
  555. result.add_fallback(t)
  556. return result
  557. def install(domain, localedir=None, codeset=_unspecified, names=None):
  558. t = translation(domain, localedir, fallback=True, codeset=codeset)
  559. t.install(names)
  560. # a mapping b/w domains and locale directories
  561. _localedirs = {}
  562. # a mapping b/w domains and codesets
  563. _localecodesets = {}
  564. # current global domain, `messages' used for compatibility w/ GNU gettext
  565. _current_domain = 'messages'
  566. def textdomain(domain=None):
  567. global _current_domain
  568. if domain is not None:
  569. _current_domain = domain
  570. return _current_domain
  571. def bindtextdomain(domain, localedir=None):
  572. global _localedirs
  573. if localedir is not None:
  574. _localedirs[domain] = localedir
  575. return _localedirs.get(domain, _default_localedir)
  576. def bind_textdomain_codeset(domain, codeset=None):
  577. import warnings
  578. warnings.warn('bind_textdomain_codeset() is deprecated',
  579. DeprecationWarning, 2)
  580. global _localecodesets
  581. if codeset is not None:
  582. _localecodesets[domain] = codeset
  583. return _localecodesets.get(domain)
  584. def dgettext(domain, message):
  585. try:
  586. t = translation(domain, _localedirs.get(domain, None))
  587. except OSError:
  588. return message
  589. return t.gettext(message)
  590. def ldgettext(domain, message):
  591. import warnings
  592. warnings.warn('ldgettext() is deprecated, use dgettext() instead',
  593. DeprecationWarning, 2)
  594. codeset = _localecodesets.get(domain)
  595. try:
  596. with warnings.catch_warnings():
  597. warnings.filterwarnings('ignore', r'.*\bparameter codeset\b.*',
  598. DeprecationWarning)
  599. t = translation(domain, _localedirs.get(domain, None), codeset=codeset)
  600. except OSError:
  601. return message.encode(codeset or locale.getpreferredencoding())
  602. with warnings.catch_warnings():
  603. warnings.filterwarnings('ignore', r'.*\blgettext\b.*',
  604. DeprecationWarning)
  605. return t.lgettext(message)
  606. def dngettext(domain, msgid1, msgid2, n):
  607. try:
  608. t = translation(domain, _localedirs.get(domain, None))
  609. except OSError:
  610. if n == 1:
  611. return msgid1
  612. else:
  613. return msgid2
  614. return t.ngettext(msgid1, msgid2, n)
  615. def ldngettext(domain, msgid1, msgid2, n):
  616. import warnings
  617. warnings.warn('ldngettext() is deprecated, use dngettext() instead',
  618. DeprecationWarning, 2)
  619. codeset = _localecodesets.get(domain)
  620. try:
  621. with warnings.catch_warnings():
  622. warnings.filterwarnings('ignore', r'.*\bparameter codeset\b.*',
  623. DeprecationWarning)
  624. t = translation(domain, _localedirs.get(domain, None), codeset=codeset)
  625. except OSError:
  626. if n == 1:
  627. tmsg = msgid1
  628. else:
  629. tmsg = msgid2
  630. return tmsg.encode(codeset or locale.getpreferredencoding())
  631. with warnings.catch_warnings():
  632. warnings.filterwarnings('ignore', r'.*\blngettext\b.*',
  633. DeprecationWarning)
  634. return t.lngettext(msgid1, msgid2, n)
  635. def dpgettext(domain, context, message):
  636. try:
  637. t = translation(domain, _localedirs.get(domain, None))
  638. except OSError:
  639. return message
  640. return t.pgettext(context, message)
  641. def dnpgettext(domain, context, msgid1, msgid2, n):
  642. try:
  643. t = translation(domain, _localedirs.get(domain, None))
  644. except OSError:
  645. if n == 1:
  646. return msgid1
  647. else:
  648. return msgid2
  649. return t.npgettext(context, msgid1, msgid2, n)
  650. def gettext(message):
  651. return dgettext(_current_domain, message)
  652. def lgettext(message):
  653. import warnings
  654. warnings.warn('lgettext() is deprecated, use gettext() instead',
  655. DeprecationWarning, 2)
  656. with warnings.catch_warnings():
  657. warnings.filterwarnings('ignore', r'.*\bldgettext\b.*',
  658. DeprecationWarning)
  659. return ldgettext(_current_domain, message)
  660. def ngettext(msgid1, msgid2, n):
  661. return dngettext(_current_domain, msgid1, msgid2, n)
  662. def lngettext(msgid1, msgid2, n):
  663. import warnings
  664. warnings.warn('lngettext() is deprecated, use ngettext() instead',
  665. DeprecationWarning, 2)
  666. with warnings.catch_warnings():
  667. warnings.filterwarnings('ignore', r'.*\bldngettext\b.*',
  668. DeprecationWarning)
  669. return ldngettext(_current_domain, msgid1, msgid2, n)
  670. def pgettext(context, message):
  671. return dpgettext(_current_domain, context, message)
  672. def npgettext(context, msgid1, msgid2, n):
  673. return dnpgettext(_current_domain, context, msgid1, msgid2, n)
  674. # dcgettext() has been deemed unnecessary and is not implemented.
  675. # James Henstridge's Catalog constructor from GNOME gettext. Documented usage
  676. # was:
  677. #
  678. # import gettext
  679. # cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
  680. # _ = cat.gettext
  681. # print _('Hello World')
  682. # The resulting catalog object currently don't support access through a
  683. # dictionary API, which was supported (but apparently unused) in GNOME
  684. # gettext.
  685. Catalog = translation