API reference¶
Here are examples of automodule
, autoclass
, and autofunction
directives.
automodule¶
.. automodule:: babel.units
:members:
:noindex:
- babel.units.format_compound_unit(numerator_value: str | float | decimal.Decimal, numerator_unit: str | None = None, denominator_value: str | float | decimal.Decimal = 1, denominator_unit: str | None = None, length: Literal['short', 'long', 'narrow'] = 'long', format: str | None = None, locale: Locale | str | None = 'en_US_POSIX', *, numbering_system: Literal['default'] | str = 'latn') str | None [source]¶
Format a compound number value, i.e. “kilometers per hour” or similar.
Both unit specifiers are optional to allow for formatting of arbitrary values still according to the locale’s general “per” formatting specifier.
>>> format_compound_unit(7, denominator_value=11, length="short", locale="pt") '7/11'
>>> format_compound_unit(150, "kilometer", denominator_unit="hour", locale="sv") '150 kilometer per timme'
>>> format_compound_unit(150, "kilowatt", denominator_unit="year", locale="fi") '150 kilowattia / vuosi'
>>> format_compound_unit(32.5, "ton", 15, denominator_unit="hour", locale="en") '32.5 tons per 15 hours'
>>> format_compound_unit(1234.5, "ton", 15, denominator_unit="hour", locale="ar_EG", numbering_system="arab") '1٬234٫5 طن لكل 15 ساعة'
>>> format_compound_unit(160, denominator_unit="square-meter", locale="fr") '160 par m\xe8tre carr\xe9'
>>> format_compound_unit(4, "meter", "ratakisko", length="short", locale="fi") '4 m/ratakisko'
>>> format_compound_unit(35, "minute", denominator_unit="nautical-mile", locale="sv") '35 minuter per nautisk mil'
>>> from babel.numbers import format_currency >>> format_compound_unit(format_currency(35, "JPY", locale="de"), denominator_unit="liter", locale="de") '35\xa0\xa5 pro Liter'
See https://www.unicode.org/reports/tr35/tr35-general.html#perUnitPatterns
- Parameters:
numerator_value – The numerator value. This may be a string, in which case it is considered preformatted and the unit is ignored.
numerator_unit – The numerator unit. See format_unit.
denominator_value – The denominator value. This may be a string, in which case it is considered preformatted and the unit is ignored.
denominator_unit – The denominator unit. See format_unit.
length – The formatting length. “short”, “long” or “narrow”
format – An optional format, as accepted by format_decimal.
locale – the Locale object or locale identifier
numbering_system – The numbering system used for formatting number symbols. Defaults to “latn”. The special value “default” will use the default numbering system of the locale.
- Returns:
A formatted compound value.
- Raises:
UnsupportedNumberingSystemError – If the numbering system is not supported by the locale.
- babel.units.format_unit(value: str | float | decimal.Decimal, measurement_unit: str, length: Literal['short', 'long', 'narrow'] = 'long', format: str | None = None, locale: Locale | str | None = 'en_US_POSIX', *, numbering_system: Literal['default'] | str = 'latn') str [source]¶
Format a value of a given unit.
Values are formatted according to the locale’s usual pluralization rules and number formats.
>>> format_unit(12, 'length-meter', locale='ro_RO') u'12 metri' >>> format_unit(15.5, 'length-mile', locale='fi_FI') u'15,5 mailia' >>> format_unit(1200, 'pressure-millimeter-ofhg', locale='nb') u'1\xa0200 millimeter kvikks\xf8lv' >>> format_unit(270, 'ton', locale='en') u'270 tons' >>> format_unit(1234.5, 'kilogram', locale='ar_EG', numbering_system='default') u'1٬234٫5 كيلوغرام'
Number formats may be overridden with the
format
parameter.>>> import decimal >>> format_unit(decimal.Decimal("-42.774"), 'temperature-celsius', 'short', format='#.0', locale='fr') u'-42,8\u202f\xb0C'
The locale’s usual pluralization rules are respected.
>>> format_unit(1, 'length-meter', locale='ro_RO') u'1 metru' >>> format_unit(0, 'length-mile', locale='cy') u'0 mi' >>> format_unit(1, 'length-mile', locale='cy') u'1 filltir' >>> format_unit(3, 'length-mile', locale='cy') u'3 milltir'
>>> format_unit(15, 'length-horse', locale='fi') Traceback (most recent call last): ... UnknownUnitError: length-horse is not a known unit in fi
Added in version 2.2.0.
- Parameters:
value – the value to format. If this is a string, no number formatting will be attempted.
measurement_unit – the code of a measurement unit. Known units can be found in the CLDR Unit Validity XML file: https://unicode.org/repos/cldr/tags/latest/common/validity/unit.xml
length – “short”, “long” or “narrow”
format – An optional format, as accepted by format_decimal.
locale – the Locale object or locale identifier
numbering_system – The numbering system used for formatting number symbols. Defaults to “latn”. The special value “default” will use the default numbering system of the locale.
- Raises:
UnsupportedNumberingSystemError – If the numbering system is not supported by the locale.
- babel.units.get_unit_name(measurement_unit: str, length: Literal['short', 'long', 'narrow'] = 'long', locale: Locale | str | None = 'en_US_POSIX') str | None [source]¶
Get the display name for a measurement unit in the given locale.
>>> get_unit_name("radian", locale="en") 'radians'
Unknown units will raise exceptions:
>>> get_unit_name("battery", locale="fi") Traceback (most recent call last): ... UnknownUnitError: battery/long is not a known unit/length in fi
- Parameters:
measurement_unit – the code of a measurement unit. Known units can be found in the CLDR Unit Validity XML file: https://unicode.org/repos/cldr/tags/latest/common/validity/unit.xml
length – “short”, “long” or “narrow”
locale – the Locale object or locale identifier
- Returns:
The unit display name, or None.
autoclass¶
.. autoclass:: babel.support.Format
:members:
:noindex:
- class babel.support.Format(locale: Locale | str, tzinfo: datetime.tzinfo | None = None, *, numbering_system: Literal['default'] | str = 'latn')[source]¶
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'
Methods
compact_currency
(number, currency[, ...])Return a number in the given currency formatted for the locale using the compact number format.
compact_decimal
(number[, format_type, ...])Return a number formatted in compact form for the locale.
currency
(number, currency)Return a number in the given currency formatted for the locale.
date
([date, format])Return a date formatted according to the given pattern.
datetime
([datetime, format])Return a date and time formatted according to the given pattern.
decimal
(number[, format])Return a decimal number formatted for the locale.
number
(number)Return an integer number formatted for the locale.
percent
(number[, format])Return a number formatted as percentage for the locale.
scientific
(number)Return a number formatted using scientific notation for the locale.
time
([time, format])Return a time formatted according to the given pattern.
timedelta
(delta[, granularity, threshold, ...])Return a time delta according to the rules of the given locale.
- compact_currency(number: float | decimal.Decimal | str, currency: str, format_type: Literal['short'] = 'short', fraction_digits: int = 0) str [source]¶
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 [source]¶
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 | str, currency: str) str [source]¶
Return a number in the given currency formatted for the locale.
- date(date: datetime.date | None = None, format: _PredefinedTimeFormat | str = 'medium') str [source]¶
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 [source]¶
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 | str, format: str | None = None) str [source]¶
Return a decimal number formatted for the locale.
>>> fmt = Format('en_US') >>> fmt.decimal(1.2345) u'1.234'
- number(number: float | Decimal | str) str [source]¶
Return an integer number formatted for the locale.
>>> fmt = Format('en_US') >>> fmt.number(1099) u'1,099'
- percent(number: float | Decimal | str, format: str | None = None) str [source]¶
Return a number formatted as percentage for the locale.
>>> fmt = Format('en_US') >>> fmt.percent(0.34) u'34%'
- scientific(number: float | Decimal | str) str [source]¶
Return a number formatted using scientific notation for the locale.
- time(time: datetime.time | datetime.datetime | None = None, format: _PredefinedTimeFormat | str = 'medium') str [source]¶
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 [source]¶
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'
autofunction¶
.. autofunction:: babel.util.distinct
- babel.util.distinct(iterable: Iterable[_T]) Generator[_T, None, None] [source]
Yield all items in an iterable collection that are distinct.
Unlike when using sets for a similar effect, the original ordering of the items in the collection is preserved by this function.
>>> print(list(distinct([1, 2, 1, 3, 4, 4]))) [1, 2, 3, 4] >>> print(list(distinct('foobar'))) ['f', 'o', 'b', 'a', 'r']
- Parameters:
iterable – the iterable collection providing the data