support.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. """
  2. babel.support
  3. ~~~~~~~~~~~~~
  4. Several classes and functions that help with integrating and using Babel
  5. in applications.
  6. .. note: the code in this module is not used by Babel itself
  7. :copyright: (c) 2013-2026 by the Babel Team.
  8. :license: BSD, see LICENSE for more details.
  9. """
  10. from __future__ import annotations
  11. import gettext
  12. import locale
  13. import os
  14. from collections.abc import Iterator
  15. from typing import TYPE_CHECKING, Any, Callable, Iterable, Literal
  16. from babel.core import Locale
  17. from babel.dates import format_date, format_datetime, format_time, format_timedelta
  18. from babel.numbers import (
  19. format_compact_currency,
  20. format_compact_decimal,
  21. format_currency,
  22. format_decimal,
  23. format_percent,
  24. format_scientific,
  25. )
  26. if TYPE_CHECKING:
  27. import datetime as _datetime
  28. from decimal import Decimal
  29. from babel.dates import _PredefinedTimeFormat
  30. class Format:
  31. """Wrapper class providing the various date and number formatting functions
  32. bound to a specific locale and time-zone.
  33. >>> from babel.util import UTC
  34. >>> from datetime import date
  35. >>> fmt = Format('en_US', UTC)
  36. >>> fmt.date(date(2007, 4, 1))
  37. 'Apr 1, 2007'
  38. >>> fmt.decimal(1.2345)
  39. '1.234'
  40. """
  41. def __init__(
  42. self,
  43. locale: Locale | str,
  44. tzinfo: _datetime.tzinfo | None = None,
  45. *,
  46. numbering_system: Literal["default"] | str = "latn",
  47. ) -> None:
  48. """Initialize the formatter.
  49. :param locale: the locale identifier or `Locale` instance
  50. :param tzinfo: the time-zone info (a `tzinfo` instance or `None`)
  51. :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
  52. The special value "default" will use the default numbering system of the locale.
  53. """
  54. self.locale = Locale.parse(locale)
  55. self.tzinfo = tzinfo
  56. self.numbering_system = numbering_system
  57. def date(
  58. self,
  59. date: _datetime.date | None = None,
  60. format: _PredefinedTimeFormat | str = 'medium',
  61. ) -> str:
  62. """Return a date formatted according to the given pattern.
  63. >>> from datetime import date
  64. >>> fmt = Format('en_US')
  65. >>> fmt.date(date(2007, 4, 1))
  66. 'Apr 1, 2007'
  67. """
  68. return format_date(date, format, locale=self.locale)
  69. def datetime(
  70. self,
  71. datetime: _datetime.date | None = None,
  72. format: _PredefinedTimeFormat | str = 'medium',
  73. ) -> str:
  74. """Return a date and time formatted according to the given pattern.
  75. >>> from datetime import datetime
  76. >>> from babel.dates import get_timezone
  77. >>> fmt = Format('en_US', tzinfo=get_timezone('US/Eastern'))
  78. >>> fmt.datetime(datetime(2007, 4, 1, 15, 30))
  79. 'Apr 1, 2007, 11:30:00\\u202fAM'
  80. """
  81. return format_datetime(datetime, format, tzinfo=self.tzinfo, locale=self.locale)
  82. def time(
  83. self,
  84. time: _datetime.time | _datetime.datetime | None = None,
  85. format: _PredefinedTimeFormat | str = 'medium',
  86. ) -> str:
  87. """Return a time formatted according to the given pattern.
  88. >>> from datetime import datetime
  89. >>> from babel.dates import get_timezone
  90. >>> fmt = Format('en_US', tzinfo=get_timezone('US/Eastern'))
  91. >>> fmt.time(datetime(2007, 4, 1, 15, 30))
  92. '11:30:00\\u202fAM'
  93. """
  94. return format_time(time, format, tzinfo=self.tzinfo, locale=self.locale)
  95. def timedelta(
  96. self,
  97. delta: _datetime.timedelta | int,
  98. granularity: Literal[
  99. "year",
  100. "month",
  101. "week",
  102. "day",
  103. "hour",
  104. "minute",
  105. "second",
  106. ] = "second",
  107. threshold: float = 0.85,
  108. format: Literal["narrow", "short", "medium", "long"] = "long",
  109. add_direction: bool = False,
  110. ) -> str:
  111. """Return a time delta according to the rules of the given locale.
  112. >>> from datetime import timedelta
  113. >>> fmt = Format('en_US')
  114. >>> fmt.timedelta(timedelta(weeks=11))
  115. '3 months'
  116. """
  117. return format_timedelta(
  118. delta,
  119. granularity=granularity,
  120. threshold=threshold,
  121. format=format,
  122. add_direction=add_direction,
  123. locale=self.locale,
  124. )
  125. def number(self, number: float | Decimal | str) -> str:
  126. """Return an integer number formatted for the locale.
  127. >>> fmt = Format('en_US')
  128. >>> fmt.number(1099)
  129. '1,099'
  130. """
  131. return format_decimal(
  132. number,
  133. locale=self.locale,
  134. numbering_system=self.numbering_system,
  135. )
  136. def decimal(self, number: float | Decimal | str, format: str | None = None) -> str:
  137. """Return a decimal number formatted for the locale.
  138. >>> fmt = Format('en_US')
  139. >>> fmt.decimal(1.2345)
  140. '1.234'
  141. """
  142. return format_decimal(
  143. number,
  144. format,
  145. locale=self.locale,
  146. numbering_system=self.numbering_system,
  147. )
  148. def compact_decimal(
  149. self,
  150. number: float | Decimal | str,
  151. format_type: Literal['short', 'long'] = 'short',
  152. fraction_digits: int = 0,
  153. ) -> str:
  154. """Return a number formatted in compact form for the locale.
  155. >>> fmt = Format('en_US')
  156. >>> fmt.compact_decimal(123456789)
  157. '123M'
  158. >>> fmt.compact_decimal(1234567, format_type='long', fraction_digits=2)
  159. '1.23 million'
  160. """
  161. return format_compact_decimal(
  162. number,
  163. format_type=format_type,
  164. fraction_digits=fraction_digits,
  165. locale=self.locale,
  166. numbering_system=self.numbering_system,
  167. )
  168. def currency(self, number: float | Decimal | str, currency: str) -> str:
  169. """Return a number in the given currency formatted for the locale."""
  170. return format_currency(
  171. number,
  172. currency,
  173. locale=self.locale,
  174. numbering_system=self.numbering_system,
  175. )
  176. def compact_currency(
  177. self,
  178. number: float | Decimal | str,
  179. currency: str,
  180. format_type: Literal['short'] = 'short',
  181. fraction_digits: int = 0,
  182. ) -> str:
  183. """Return a number in the given currency formatted for the locale
  184. using the compact number format.
  185. >>> Format('en_US').compact_currency(1234567, "USD", format_type='short', fraction_digits=2)
  186. '$1.23M'
  187. """
  188. return format_compact_currency(
  189. number,
  190. currency,
  191. format_type=format_type,
  192. fraction_digits=fraction_digits,
  193. locale=self.locale,
  194. numbering_system=self.numbering_system,
  195. )
  196. def percent(self, number: float | Decimal | str, format: str | None = None) -> str:
  197. """Return a number formatted as percentage for the locale.
  198. >>> fmt = Format('en_US')
  199. >>> fmt.percent(0.34)
  200. '34%'
  201. """
  202. return format_percent(
  203. number,
  204. format,
  205. locale=self.locale,
  206. numbering_system=self.numbering_system,
  207. )
  208. def scientific(self, number: float | Decimal | str) -> str:
  209. """Return a number formatted using scientific notation for the locale."""
  210. return format_scientific(
  211. number,
  212. locale=self.locale,
  213. numbering_system=self.numbering_system,
  214. )
  215. class LazyProxy:
  216. """Class for proxy objects that delegate to a specified function to evaluate
  217. the actual object.
  218. >>> def greeting(name='world'):
  219. ... return 'Hello, %s!' % name
  220. >>> lazy_greeting = LazyProxy(greeting, name='Joe')
  221. >>> print(lazy_greeting)
  222. Hello, Joe!
  223. >>> ' ' + lazy_greeting
  224. ' Hello, Joe!'
  225. >>> '(%s)' % lazy_greeting
  226. '(Hello, Joe!)'
  227. This can be used, for example, to implement lazy translation functions that
  228. delay the actual translation until the string is actually used. The
  229. rationale for such behavior is that the locale of the user may not always
  230. be available. In web applications, you only know the locale when processing
  231. a request.
  232. The proxy implementation attempts to be as complete as possible, so that
  233. the lazy objects should mostly work as expected, for example for sorting:
  234. >>> greetings = [
  235. ... LazyProxy(greeting, 'world'),
  236. ... LazyProxy(greeting, 'Joe'),
  237. ... LazyProxy(greeting, 'universe'),
  238. ... ]
  239. >>> greetings.sort()
  240. >>> for greeting in greetings:
  241. ... print(greeting)
  242. Hello, Joe!
  243. Hello, universe!
  244. Hello, world!
  245. """
  246. __slots__ = [
  247. '_func',
  248. '_args',
  249. '_kwargs',
  250. '_value',
  251. '_is_cache_enabled',
  252. '_attribute_error',
  253. ]
  254. if TYPE_CHECKING:
  255. _func: Callable[..., Any]
  256. _args: tuple[Any, ...]
  257. _kwargs: dict[str, Any]
  258. _is_cache_enabled: bool
  259. _value: Any
  260. _attribute_error: AttributeError | None
  261. def __init__(
  262. self,
  263. func: Callable[..., Any],
  264. *args: Any,
  265. enable_cache: bool = True,
  266. **kwargs: Any,
  267. ) -> None:
  268. # Avoid triggering our own __setattr__ implementation
  269. object.__setattr__(self, '_func', func)
  270. object.__setattr__(self, '_args', args)
  271. object.__setattr__(self, '_kwargs', kwargs)
  272. object.__setattr__(self, '_is_cache_enabled', enable_cache)
  273. object.__setattr__(self, '_value', None)
  274. object.__setattr__(self, '_attribute_error', None)
  275. @property
  276. def value(self) -> Any:
  277. if self._value is None:
  278. try:
  279. value = self._func(*self._args, **self._kwargs)
  280. except AttributeError as error:
  281. object.__setattr__(self, '_attribute_error', error)
  282. raise
  283. if not self._is_cache_enabled:
  284. return value
  285. object.__setattr__(self, '_value', value)
  286. return self._value
  287. def __contains__(self, key: object) -> bool:
  288. return key in self.value
  289. def __bool__(self) -> bool:
  290. return bool(self.value)
  291. def __dir__(self) -> list[str]:
  292. return dir(self.value)
  293. def __iter__(self) -> Iterator[Any]:
  294. return iter(self.value)
  295. def __len__(self) -> int:
  296. return len(self.value)
  297. def __str__(self) -> str:
  298. return str(self.value)
  299. def __add__(self, other: object) -> Any:
  300. return self.value + other
  301. def __radd__(self, other: object) -> Any:
  302. return other + self.value
  303. def __mod__(self, other: object) -> Any:
  304. return self.value % other
  305. def __rmod__(self, other: object) -> Any:
  306. return other % self.value
  307. def __mul__(self, other: object) -> Any:
  308. return self.value * other
  309. def __rmul__(self, other: object) -> Any:
  310. return other * self.value
  311. def __call__(self, *args: Any, **kwargs: Any) -> Any:
  312. return self.value(*args, **kwargs)
  313. def __lt__(self, other: object) -> bool:
  314. return self.value < other
  315. def __le__(self, other: object) -> bool:
  316. return self.value <= other
  317. def __eq__(self, other: object) -> bool:
  318. return self.value == other
  319. def __ne__(self, other: object) -> bool:
  320. return self.value != other
  321. def __gt__(self, other: object) -> bool:
  322. return self.value > other
  323. def __ge__(self, other: object) -> bool:
  324. return self.value >= other
  325. def __delattr__(self, name: str) -> None:
  326. delattr(self.value, name)
  327. def __getattr__(self, name: str) -> Any:
  328. if self._attribute_error is not None:
  329. raise self._attribute_error
  330. return getattr(self.value, name)
  331. def __setattr__(self, name: str, value: Any) -> None:
  332. setattr(self.value, name, value)
  333. def __delitem__(self, key: Any) -> None:
  334. del self.value[key]
  335. def __getitem__(self, key: Any) -> Any:
  336. return self.value[key]
  337. def __setitem__(self, key: Any, value: Any) -> None:
  338. self.value[key] = value
  339. def __copy__(self) -> LazyProxy:
  340. return LazyProxy(
  341. self._func,
  342. enable_cache=self._is_cache_enabled,
  343. *self._args, # noqa: B026
  344. **self._kwargs,
  345. )
  346. def __deepcopy__(self, memo: Any) -> LazyProxy:
  347. from copy import deepcopy
  348. return LazyProxy(
  349. deepcopy(self._func, memo),
  350. enable_cache=deepcopy(self._is_cache_enabled, memo),
  351. *deepcopy(self._args, memo), # noqa: B026
  352. **deepcopy(self._kwargs, memo),
  353. )
  354. class NullTranslations(gettext.NullTranslations):
  355. if TYPE_CHECKING:
  356. _info: dict[str, str]
  357. _fallback: NullTranslations | None
  358. DEFAULT_DOMAIN = None
  359. def __init__(self, fp: gettext._TranslationsReader | None = None) -> None:
  360. """Initialize a simple translations class which is not backed by a
  361. real catalog. Behaves similar to gettext.NullTranslations but also
  362. offers Babel's on *gettext methods (e.g. 'dgettext()').
  363. :param fp: a file-like object (ignored in this class)
  364. """
  365. # These attributes are set by gettext.NullTranslations when a catalog
  366. # is parsed (fp != None). Ensure that they are always present because
  367. # some *gettext methods (including '.gettext()') rely on the attributes.
  368. self._catalog: dict[tuple[str, Any] | str, str] = {}
  369. self.plural: Callable[[float | Decimal], int] = lambda n: int(n != 1)
  370. super().__init__(fp=fp)
  371. self.files = list(filter(None, [getattr(fp, 'name', None)]))
  372. self.domain = self.DEFAULT_DOMAIN
  373. self._domains: dict[str, NullTranslations] = {}
  374. def dgettext(self, domain: str, message: str) -> str:
  375. """Like ``gettext()``, but look the message up in the specified
  376. domain.
  377. """
  378. return self._domains.get(domain, self).gettext(message)
  379. def ldgettext(self, domain: str, message: str) -> str:
  380. """Like ``lgettext()``, but look the message up in the specified
  381. domain.
  382. """
  383. import warnings
  384. warnings.warn(
  385. 'ldgettext() is deprecated, use dgettext() instead',
  386. DeprecationWarning,
  387. stacklevel=2,
  388. )
  389. return self._domains.get(domain, self).lgettext(message)
  390. def udgettext(self, domain: str, message: str) -> str:
  391. """Like ``ugettext()``, but look the message up in the specified
  392. domain.
  393. """
  394. return self._domains.get(domain, self).ugettext(message)
  395. # backward compatibility with 0.9
  396. dugettext = udgettext
  397. def dngettext(self, domain: str, singular: str, plural: str, num: int) -> str:
  398. """Like ``ngettext()``, but look the message up in the specified
  399. domain.
  400. """
  401. return self._domains.get(domain, self).ngettext(singular, plural, num)
  402. def ldngettext(self, domain: str, singular: str, plural: str, num: int) -> str:
  403. """Like ``lngettext()``, but look the message up in the specified
  404. domain.
  405. """
  406. import warnings
  407. warnings.warn(
  408. 'ldngettext() is deprecated, use dngettext() instead',
  409. DeprecationWarning,
  410. stacklevel=2,
  411. )
  412. return self._domains.get(domain, self).lngettext(singular, plural, num)
  413. def udngettext(self, domain: str, singular: str, plural: str, num: int) -> str:
  414. """Like ``ungettext()`` but look the message up in the specified
  415. domain.
  416. """
  417. return self._domains.get(domain, self).ungettext(singular, plural, num)
  418. # backward compatibility with 0.9
  419. dungettext = udngettext
  420. # Most of the downwards code, until it gets included in stdlib, from:
  421. # https://bugs.python.org/file10036/gettext-pgettext.patch
  422. #
  423. # The encoding of a msgctxt and a msgid in a .mo file is
  424. # msgctxt + "\x04" + msgid (gettext version >= 0.15)
  425. CONTEXT_ENCODING = '%s\x04%s'
  426. def pgettext(self, context: str, message: str) -> str | object:
  427. """Look up the `context` and `message` id in the catalog and return the
  428. corresponding message string, as an 8-bit string encoded with the
  429. catalog's charset encoding, if known. If there is no entry in the
  430. catalog for the `message` id and `context` , and a fallback has been
  431. set, the look up is forwarded to the fallback's ``pgettext()``
  432. method. Otherwise, the `message` id is returned.
  433. """
  434. ctxt_msg_id = self.CONTEXT_ENCODING % (context, message)
  435. missing = object()
  436. tmsg = self._catalog.get(ctxt_msg_id, missing)
  437. if tmsg is missing:
  438. tmsg = self._catalog.get((ctxt_msg_id, self.plural(1)), missing)
  439. if tmsg is not missing:
  440. return tmsg
  441. if self._fallback:
  442. return self._fallback.pgettext(context, message)
  443. return message
  444. def lpgettext(self, context: str, message: str) -> str | bytes | object:
  445. """Equivalent to ``pgettext()``, but the translation is returned in the
  446. preferred system encoding, if no other encoding was explicitly set with
  447. ``bind_textdomain_codeset()``.
  448. """
  449. import warnings
  450. warnings.warn(
  451. 'lpgettext() is deprecated, use pgettext() instead',
  452. DeprecationWarning,
  453. stacklevel=2,
  454. )
  455. tmsg = self.pgettext(context, message)
  456. encoding = getattr(self, "_output_charset", None) or locale.getpreferredencoding()
  457. return tmsg.encode(encoding) if isinstance(tmsg, str) else tmsg
  458. def npgettext(self, context: str, singular: str, plural: str, num: int) -> str:
  459. """Do a plural-forms lookup of a message id. `singular` is used as the
  460. message id for purposes of lookup in the catalog, while `num` is used to
  461. determine which plural form to use. The returned message string is an
  462. 8-bit string encoded with the catalog's charset encoding, if known.
  463. If the message id for `context` is not found in the catalog, and a
  464. fallback is specified, the request is forwarded to the fallback's
  465. ``npgettext()`` method. Otherwise, when ``num`` is 1 ``singular`` is
  466. returned, and ``plural`` is returned in all other cases.
  467. """
  468. ctxt_msg_id = self.CONTEXT_ENCODING % (context, singular)
  469. try:
  470. tmsg = self._catalog[(ctxt_msg_id, self.plural(num))]
  471. return tmsg
  472. except KeyError:
  473. if self._fallback:
  474. return self._fallback.npgettext(context, singular, plural, num)
  475. if num == 1:
  476. return singular
  477. else:
  478. return plural
  479. def lnpgettext(self, context: str, singular: str, plural: str, num: int) -> str | bytes:
  480. """Equivalent to ``npgettext()``, but the translation is returned in the
  481. preferred system encoding, if no other encoding was explicitly set with
  482. ``bind_textdomain_codeset()``.
  483. """
  484. import warnings
  485. warnings.warn(
  486. 'lnpgettext() is deprecated, use npgettext() instead',
  487. DeprecationWarning,
  488. stacklevel=2,
  489. )
  490. ctxt_msg_id = self.CONTEXT_ENCODING % (context, singular)
  491. try:
  492. tmsg = self._catalog[(ctxt_msg_id, self.plural(num))]
  493. encoding = getattr(self, "_output_charset", None) or locale.getpreferredencoding()
  494. return tmsg.encode(encoding)
  495. except KeyError:
  496. if self._fallback:
  497. return self._fallback.lnpgettext(context, singular, plural, num)
  498. if num == 1:
  499. return singular
  500. else:
  501. return plural
  502. def upgettext(self, context: str, message: str) -> str:
  503. """Look up the `context` and `message` id in the catalog and return the
  504. corresponding message string, as a Unicode string. If there is no entry
  505. in the catalog for the `message` id and `context`, and a fallback has
  506. been set, the look up is forwarded to the fallback's ``upgettext()``
  507. method. Otherwise, the `message` id is returned.
  508. """
  509. ctxt_message_id = self.CONTEXT_ENCODING % (context, message)
  510. missing = object()
  511. tmsg = self._catalog.get(ctxt_message_id, missing)
  512. if tmsg is missing:
  513. if self._fallback:
  514. return self._fallback.upgettext(context, message)
  515. return str(message)
  516. assert isinstance(tmsg, str)
  517. return tmsg
  518. def unpgettext(self, context: str, singular: str, plural: str, num: int) -> str:
  519. """Do a plural-forms lookup of a message id. `singular` is used as the
  520. message id for purposes of lookup in the catalog, while `num` is used to
  521. determine which plural form to use. The returned message string is a
  522. Unicode string.
  523. If the message id for `context` is not found in the catalog, and a
  524. fallback is specified, the request is forwarded to the fallback's
  525. ``unpgettext()`` method. Otherwise, when `num` is 1 `singular` is
  526. returned, and `plural` is returned in all other cases.
  527. """
  528. ctxt_message_id = self.CONTEXT_ENCODING % (context, singular)
  529. try:
  530. tmsg = self._catalog[(ctxt_message_id, self.plural(num))]
  531. except KeyError:
  532. if self._fallback:
  533. return self._fallback.unpgettext(context, singular, plural, num)
  534. tmsg = str(singular) if num == 1 else str(plural)
  535. return tmsg
  536. def dpgettext(self, domain: str, context: str, message: str) -> str | object:
  537. """Like `pgettext()`, but look the message up in the specified
  538. `domain`.
  539. """
  540. return self._domains.get(domain, self).pgettext(context, message)
  541. def udpgettext(self, domain: str, context: str, message: str) -> str:
  542. """Like `upgettext()`, but look the message up in the specified
  543. `domain`.
  544. """
  545. return self._domains.get(domain, self).upgettext(context, message)
  546. # backward compatibility with 0.9
  547. dupgettext = udpgettext
  548. def ldpgettext(self, domain: str, context: str, message: str) -> str | bytes | object:
  549. """Equivalent to ``dpgettext()``, but the translation is returned in the
  550. preferred system encoding, if no other encoding was explicitly set with
  551. ``bind_textdomain_codeset()``.
  552. """
  553. return self._domains.get(domain, self).lpgettext(context, message)
  554. def dnpgettext(self, domain: str, context: str, singular: str, plural: str, num: int) -> str: # fmt: skip
  555. """Like ``npgettext``, but look the message up in the specified
  556. `domain`.
  557. """
  558. return self._domains.get(domain, self).npgettext(context, singular, plural, num)
  559. def udnpgettext(self, domain: str, context: str, singular: str, plural: str, num: int) -> str: # fmt: skip
  560. """Like ``unpgettext``, but look the message up in the specified
  561. `domain`.
  562. """
  563. return self._domains.get(domain, self).unpgettext(context, singular, plural, num)
  564. # backward compatibility with 0.9
  565. dunpgettext = udnpgettext
  566. def ldnpgettext(
  567. self,
  568. domain: str,
  569. context: str,
  570. singular: str,
  571. plural: str,
  572. num: int,
  573. ) -> str | bytes:
  574. """Equivalent to ``dnpgettext()``, but the translation is returned in
  575. the preferred system encoding, if no other encoding was explicitly set
  576. with ``bind_textdomain_codeset()``.
  577. """
  578. return self._domains.get(domain, self).lnpgettext(context, singular, plural, num)
  579. ugettext = gettext.NullTranslations.gettext
  580. ungettext = gettext.NullTranslations.ngettext
  581. class Translations(NullTranslations, gettext.GNUTranslations):
  582. """An extended translation catalog class."""
  583. DEFAULT_DOMAIN = 'messages'
  584. def __init__(
  585. self,
  586. fp: gettext._TranslationsReader | None = None,
  587. domain: str | None = None,
  588. ):
  589. """Initialize the translations catalog.
  590. :param fp: the file-like object the translation should be read from
  591. :param domain: the message domain (default: 'messages')
  592. """
  593. super().__init__(fp=fp)
  594. self.domain = domain or self.DEFAULT_DOMAIN
  595. ugettext = gettext.GNUTranslations.gettext
  596. ungettext = gettext.GNUTranslations.ngettext
  597. @classmethod
  598. def load(
  599. cls,
  600. dirname: str | os.PathLike[str] | None = None,
  601. locales: Iterable[str | Locale] | Locale | str | None = None,
  602. domain: str | None = None,
  603. ) -> NullTranslations:
  604. """Load translations from the given directory.
  605. :param dirname: the directory containing the ``MO`` files
  606. :param locales: the list of locales in order of preference (items in
  607. this list can be either `Locale` objects or locale
  608. strings)
  609. :param domain: the message domain (default: 'messages')
  610. """
  611. if not domain:
  612. domain = cls.DEFAULT_DOMAIN
  613. filename = gettext.find(domain, dirname, _locales_to_names(locales))
  614. if not filename:
  615. return NullTranslations()
  616. with open(filename, 'rb') as fp:
  617. return cls(fp=fp, domain=domain)
  618. def __repr__(self) -> str:
  619. version = self._info.get('project-id-version')
  620. return f'<{type(self).__name__}: "{version}">'
  621. def add(self, translations: Translations, merge: bool = True):
  622. """Add the given translations to the catalog.
  623. If the domain of the translations is different than that of the
  624. current catalog, they are added as a catalog that is only accessible
  625. by the various ``d*gettext`` functions.
  626. :param translations: the `Translations` instance with the messages to
  627. add
  628. :param merge: whether translations for message domains that have
  629. already been added should be merged with the existing
  630. translations
  631. """
  632. domain = getattr(translations, 'domain', self.DEFAULT_DOMAIN)
  633. if merge and domain == self.domain:
  634. return self.merge(translations)
  635. existing = self._domains.get(domain)
  636. if merge and isinstance(existing, Translations):
  637. existing.merge(translations)
  638. else:
  639. translations.add_fallback(self)
  640. self._domains[domain] = translations
  641. return self
  642. def merge(self, translations: Translations):
  643. """Merge the given translations into the catalog.
  644. Message translations in the specified catalog override any messages
  645. with the same identifier in the existing catalog.
  646. :param translations: the `Translations` instance with the messages to
  647. merge
  648. """
  649. if isinstance(translations, gettext.GNUTranslations):
  650. self._catalog.update(translations._catalog)
  651. if isinstance(translations, Translations):
  652. self.files.extend(translations.files)
  653. return self
  654. def _locales_to_names(
  655. locales: Iterable[str | Locale] | Locale | str | None,
  656. ) -> list[str] | None:
  657. """Normalize a `locales` argument to a list of locale names.
  658. :param locales: the list of locales in order of preference (items in
  659. this list can be either `Locale` objects or locale
  660. strings)
  661. """
  662. if locales is None:
  663. return None
  664. if isinstance(locales, Locale):
  665. return [str(locales)]
  666. if isinstance(locales, str):
  667. return [locales]
  668. return [str(locale) for locale in locales]