gettext.py 27 KB

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