support.py 27 KB

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