General Support Functionality

Babel ships a few general helpers that are not being used by Babel itself but are useful in combination with functionality provided by it.

Convenience Helpers

class babel.support.Format(locale: Locale | str, tzinfo: datetime.tzinfo | None = None, *, numbering_system: Literal['default'] | str = 'latn')

Wrapper class providing the various date and number formatting functions bound to a specific locale and time-zone.

>>> from babel.util import UTC
>>> from datetime import date
>>> fmt = Format('en_US', UTC)
>>> fmt.date(date(2007, 4, 1))
u'Apr 1, 2007'
>>> fmt.decimal(1.2345)
u'1.234'
compact_currency(number: float | decimal.Decimal | str, currency: str, format_type: Literal['short'] = 'short', fraction_digits: int = 0) str

Return a number in the given currency formatted for the locale using the compact number format.

>>> Format('en_US').compact_currency(1234567, "USD", format_type='short', fraction_digits=2)
'$1.23M'
compact_decimal(number: float | decimal.Decimal | str, format_type: Literal['short', 'long'] = 'short', fraction_digits: int = 0) str

Return a number formatted in compact form for the locale.

>>> fmt = Format('en_US')
>>> fmt.compact_decimal(123456789)
u'123M'
>>> fmt.compact_decimal(1234567, format_type='long', fraction_digits=2)
'1.23 million'
currency(number: float | decimal.Decimal | str, currency: str) str

Return a number in the given currency formatted for the locale.

date(date: datetime.date | None = None, format: _PredefinedTimeFormat | str = 'medium') str

Return a date formatted according to the given pattern.

>>> from datetime import date
>>> fmt = Format('en_US')
>>> fmt.date(date(2007, 4, 1))
u'Apr 1, 2007'
datetime(datetime: datetime.date | None = None, format: _PredefinedTimeFormat | str = 'medium') str

Return a date and time formatted according to the given pattern.

>>> from datetime import datetime
>>> from babel.dates import get_timezone
>>> fmt = Format('en_US', tzinfo=get_timezone('US/Eastern'))
>>> fmt.datetime(datetime(2007, 4, 1, 15, 30))
u'Apr 1, 2007, 11:30:00 AM'
decimal(number: float | decimal.Decimal | str, format: str | None = None) str

Return a decimal number formatted for the locale.

>>> fmt = Format('en_US')
>>> fmt.decimal(1.2345)
u'1.234'
number(number: float | decimal.Decimal | str) str

Return an integer number formatted for the locale.

>>> fmt = Format('en_US')
>>> fmt.number(1099)
u'1,099'
percent(number: float | decimal.Decimal | str, format: str | None = None) str

Return a number formatted as percentage for the locale.

>>> fmt = Format('en_US')
>>> fmt.percent(0.34)
u'34%'
scientific(number: float | decimal.Decimal | str) str

Return a number formatted using scientific notation for the locale.

time(time: datetime.time | datetime.datetime | None = None, format: _PredefinedTimeFormat | str = 'medium') str

Return a time formatted according to the given pattern.

>>> from datetime import datetime
>>> from babel.dates import get_timezone
>>> fmt = Format('en_US', tzinfo=get_timezone('US/Eastern'))
>>> fmt.time(datetime(2007, 4, 1, 15, 30))
u'11:30:00 AM'
timedelta(delta: datetime.timedelta | int, granularity: Literal['year', 'month', 'week', 'day', 'hour', 'minute', 'second'] = 'second', threshold: float = 0.85, format: Literal['narrow', 'short', 'medium', 'long'] = 'long', add_direction: bool = False) str

Return a time delta according to the rules of the given locale.

>>> from datetime import timedelta
>>> fmt = Format('en_US')
>>> fmt.timedelta(timedelta(weeks=11))
u'3 months'
class babel.support.LazyProxy(func: Callable[[...], Any], *args: Any, enable_cache: bool = True, **kwargs: Any)

Class for proxy objects that delegate to a specified function to evaluate the actual object.

>>> def greeting(name='world'):
...     return 'Hello, %s!' % name
>>> lazy_greeting = LazyProxy(greeting, name='Joe')
>>> print(lazy_greeting)
Hello, Joe!
>>> u'  ' + lazy_greeting
u'  Hello, Joe!'
>>> u'(%s)' % lazy_greeting
u'(Hello, Joe!)'

This can be used, for example, to implement lazy translation functions that delay the actual translation until the string is actually used. The rationale for such behavior is that the locale of the user may not always be available. In web applications, you only know the locale when processing a request.

The proxy implementation attempts to be as complete as possible, so that the lazy objects should mostly work as expected, for example for sorting:

>>> greetings = [
...     LazyProxy(greeting, 'world'),
...     LazyProxy(greeting, 'Joe'),
...     LazyProxy(greeting, 'universe'),
... ]
>>> greetings.sort()
>>> for greeting in greetings:
...     print(greeting)
Hello, Joe!
Hello, universe!
Hello, world!

Gettext Support

class babel.support.Translations(fp: gettext._TranslationsReader | None = None, domain: str | None = None)

An extended translation catalog class.

add(translations: Translations, merge: bool = True)

Add the given translations to the catalog.

If the domain of the translations is different than that of the current catalog, they are added as a catalog that is only accessible by the various d*gettext functions.

Parameters:
  • translations – the Translations instance with the messages to add

  • merge – whether translations for message domains that have already been added should be merged with the existing translations

classmethod load(dirname: str | os.PathLike[str] | None = None, locales: Optional[Union[Iterable[str | babel.core.Locale], str, Locale]] = None, domain: str | None = None) NullTranslations

Load translations from the given directory.

Parameters:
  • dirname – the directory containing the MO files

  • locales – the list of locales in order of preference (items in this list can be either Locale objects or locale strings)

  • domain – the message domain (default: ‘messages’)

merge(translations: Translations)

Merge the given translations into the catalog.

Message translations in the specified catalog override any messages with the same identifier in the existing catalog.

Parameters:

translations – the Translations instance with the messages to merge