| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import decimal |
| 4 |
import warnings |
| 5 |
from typing import Literal |
| 6 |
|
| 7 |
from babel.core import Locale |
| 8 |
from babel.numbers import LC_NUMERIC, format_decimal |
| 9 |
|
| 10 |
_DEPRECATED_UNIT_IDS: dict[str, str] = { |
| 11 |
# Unit IDs deprecated in CLDR 48 |
| 12 |
"concentr-permillion": "concentr-part-per-1e6", |
| 13 |
"concentr-portion": "concentr-part", |
| 14 |
"concentr-portion-per-1e9": "concentr-part-per-1e9", |
| 15 |
"permillion": "part-per-1e6", |
| 16 |
"portion": "part", |
| 17 |
"portion-per-1e9": "part-per-1e9", |
| 18 |
} |
| 19 |
|
| 20 |
|
| 21 |
class UnknownUnitError(ValueError): |
| 22 |
def __init__(self, unit: str, locale: Locale) -> None: |
| 23 |
ValueError.__init__(self, f"{unit} is not a known unit in {locale}") |
| 24 |
|
| 25 |
|
| 26 |
def get_unit_name( |
| 27 |
measurement_unit: str, |
| 28 |
length: Literal['short', 'long', 'narrow'] = 'long', |
| 29 |
locale: Locale | str | None = None, |
| 30 |
) -> str | None: |
| 31 |
""" |
| 32 |
Get the display name for a measurement unit in the given locale. |
| 33 |
|
| 34 |
>>> get_unit_name("radian", locale="en") |
| 35 |
'radians' |
| 36 |
|
| 37 |
Unknown units will raise exceptions: |
| 38 |
|
| 39 |
>>> get_unit_name("battery", locale="fi") |
| 40 |
Traceback (most recent call last): |
| 41 |
... |
| 42 |
UnknownUnitError: battery/long is not a known unit/length in fi |
| 43 |
|
| 44 |
:param measurement_unit: the code of a measurement unit. |
| 45 |
Known units can be found in the CLDR Unit Validity XML file: |
| 46 |
https://unicode.org/repos/cldr/tags/latest/common/validity/unit.xml |
| 47 |
|
| 48 |
:param length: "short", "long" or "narrow" |
| 49 |
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale. |
| 50 |
:return: The unit display name, or None. |
| 51 |
""" |
| 52 |
locale = Locale.parse(locale or LC_NUMERIC) |
| 53 |
unit = _find_unit_pattern(measurement_unit, locale=locale) |
| 54 |
if not unit: |
| 55 |
raise UnknownUnitError(unit=measurement_unit, locale=locale) |
| 56 |
return locale.unit_display_names.get(unit, {}).get(length) |
| 57 |
|
| 58 |
|
| 59 |
def _find_unit_pattern(unit_id: str, locale: Locale | str | None = None) -> str | None: |
| 60 |
""" |
| 61 |
Expand a unit into a qualified form. |
| 62 |
|
| 63 |
Known units can be found in the CLDR Unit Validity XML file: |
| 64 |
https://unicode.org/repos/cldr/tags/latest/common/validity/unit.xml |
| 65 |
|
| 66 |
>>> _find_unit_pattern("radian", locale="en") |
| 67 |
'angle-radian' |
| 68 |
|
| 69 |
Unknown values will return None. |
| 70 |
|
| 71 |
>>> _find_unit_pattern("horse", locale="en") |
| 72 |
|
| 73 |
:param unit_id: the code of a measurement unit. |
| 74 |
:return: A key to the `unit_patterns` mapping, or None. |
| 75 |
""" |
| 76 |
locale = Locale.parse(locale or LC_NUMERIC) |
| 77 |
unit_patterns: dict[str, str] = locale._data["unit_patterns"] |
| 78 |
if unit_id in unit_patterns: |
| 79 |
return unit_id |
| 80 |
|
| 81 |
# Only if a direct hit didn't work, try deprecated units... |
| 82 |
new_id = _DEPRECATED_UNIT_IDS.get(unit_id) |
| 83 |
if new_id is not None: |
| 84 |
warnings.warn( |
| 85 |
f"Unit identifier {unit_id!r} is deprecated; use {new_id!r} instead.", |
| 86 |
DeprecationWarning, |
| 87 |
stacklevel=4, |
| 88 |
) |
| 89 |
if new_id in unit_patterns: |
| 90 |
return new_id |
| 91 |
|
| 92 |
# ... and finally fuzzy matching. |
| 93 |
for unit_pattern in sorted(unit_patterns, key=len): |
| 94 |
if unit_pattern.endswith(unit_id): |
| 95 |
return unit_pattern |
| 96 |
return None |
| 97 |
|
| 98 |
|
| 99 |
def format_unit( |
| 100 |
value: str | float | decimal.Decimal, |
| 101 |
measurement_unit: str, |
| 102 |
length: Literal['short', 'long', 'narrow'] = 'long', |
| 103 |
format: str | None = None, |
| 104 |
locale: Locale | str | None = None, |
| 105 |
*, |
| 106 |
numbering_system: Literal["default"] | str = "latn", |
| 107 |
) -> str: |
| 108 |
"""Format a value of a given unit. |
| 109 |
|
| 110 |
Values are formatted according to the locale's usual pluralization rules |
| 111 |
and number formats. |
| 112 |
|
| 113 |
>>> format_unit(12, 'length-meter', locale='ro_RO') |
| 114 |
'12 metri' |
| 115 |
>>> format_unit(15.5, 'length-mile', locale='fi_FI') |
| 116 |
'15,5 mailia' |
| 117 |
>>> format_unit(1200, 'pressure-millimeter-ofhg', locale='nb') |
| 118 |
'1\\xa0200 millimeter kvikks\\xf8lv' |
| 119 |
>>> format_unit(270, 'ton', locale='en') |
| 120 |
'270 tons' |
| 121 |
>>> format_unit(1234.5, 'kilogram', locale='ar_EG', numbering_system='default') |
| 122 |
'1٬234٫5 كيلوغرام' |
| 123 |
|
| 124 |
Number formats may be overridden with the ``format`` parameter. |
| 125 |
|
| 126 |
>>> import decimal |
| 127 |
>>> format_unit(decimal.Decimal("-42.774"), 'temperature-celsius', 'short', format='#.0', locale='fr') |
| 128 |
'-42,8\\u202f\\xb0C' |
| 129 |
|
| 130 |
The locale's usual pluralization rules are respected. |
| 131 |
|
| 132 |
>>> format_unit(1, 'length-meter', locale='ro_RO') |
| 133 |
'1 metru' |
| 134 |
>>> format_unit(0, 'length-mile', locale='cy') |
| 135 |
'0 mi' |
| 136 |
>>> format_unit(1, 'length-mile', locale='cy') |
| 137 |
'1 filltir' |
| 138 |
>>> format_unit(3, 'length-mile', locale='cy') |
| 139 |
'3 milltir' |
| 140 |
|
| 141 |
>>> format_unit(15, 'length-horse', locale='fi') |
| 142 |
Traceback (most recent call last): |
| 143 |
... |
| 144 |
UnknownUnitError: length-horse is not a known unit in fi |
| 145 |
|
| 146 |
.. versionadded:: 2.2.0 |
| 147 |
|
| 148 |
:param value: the value to format. If this is a string, no number formatting will be attempted and the number is assumed to be singular for the purposes of unit formatting. |
| 149 |
:param measurement_unit: the code of a measurement unit. |
| 150 |
Known units can be found in the CLDR Unit Validity XML file: |
| 151 |
https://unicode.org/repos/cldr/tags/latest/common/validity/unit.xml |
| 152 |
:param length: "short", "long" or "narrow" |
| 153 |
:param format: An optional format, as accepted by `format_decimal`. |
| 154 |
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale. |
| 155 |
:param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn". |
| 156 |
The special value "default" will use the default numbering system of the locale. |
| 157 |
:raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale. |
| 158 |
""" |
| 159 |
locale = Locale.parse(locale or LC_NUMERIC) |
| 160 |
|
| 161 |
q_unit = _find_unit_pattern(measurement_unit, locale=locale) |
| 162 |
if not q_unit: |
| 163 |
raise UnknownUnitError(unit=measurement_unit, locale=locale) |
| 164 |
|
| 165 |
if isinstance(value, str): # Assume the value is a preformatted singular. |
| 166 |
formatted_value = value |
| 167 |
plural_form = "one" |
| 168 |
else: |
| 169 |
formatted_value = format_decimal( |
| 170 |
value, |
| 171 |
format, |
| 172 |
locale, |
| 173 |
numbering_system=numbering_system, |
| 174 |
) |
| 175 |
plural_form = locale.plural_form(value) |
| 176 |
|
| 177 |
length_patterns = locale._data["unit_patterns"][q_unit].get(length, {}) # resolves aliases |
| 178 |
# Fall back from the correct plural form to "other" |
| 179 |
# (this is specified in LDML "Lateral Inheritance") |
| 180 |
pat = length_patterns.get(plural_form) or length_patterns.get("other") |
| 181 |
if pat: |
| 182 |
return pat.format(formatted_value) |
| 183 |
|
| 184 |
# Fall back to a somewhat bad representation. |
| 185 |
# nb: This is marked as no-cover, as the current CLDR seemingly has no way for this to happen. |
| 186 |
fallback_name = get_unit_name( # pragma: no cover |
| 187 |
measurement_unit, |
| 188 |
length=length, |
| 189 |
locale=locale, |
| 190 |
) |
| 191 |
return f"{formatted_value} {fallback_name or measurement_unit}" # pragma: no cover |
| 192 |
|
| 193 |
|
| 194 |
def _find_compound_unit( |
| 195 |
numerator_unit: str, |
| 196 |
denominator_unit: str, |
| 197 |
locale: Locale | str | None = None, |
| 198 |
) -> str | None: |
| 199 |
""" |
| 200 |
Find a predefined compound unit pattern. |
| 201 |
|
| 202 |
Used internally by format_compound_unit. |
| 203 |
|
| 204 |
>>> _find_compound_unit("kilometer", "hour", locale="en") |
| 205 |
'speed-kilometer-per-hour' |
| 206 |
|
| 207 |
>>> _find_compound_unit("mile", "gallon", locale="en") |
| 208 |
'consumption-mile-per-gallon' |
| 209 |
|
| 210 |
If no predefined compound pattern can be found, `None` is returned. |
| 211 |
|
| 212 |
>>> _find_compound_unit("gallon", "mile", locale="en") |
| 213 |
|
| 214 |
>>> _find_compound_unit("horse", "purple", locale="en") |
| 215 |
|
| 216 |
:param numerator_unit: The numerator unit's identifier |
| 217 |
:param denominator_unit: The denominator unit's identifier |
| 218 |
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale. |
| 219 |
:return: A key to the `unit_patterns` mapping, or None. |
| 220 |
:rtype: str|None |
| 221 |
""" |
| 222 |
locale = Locale.parse(locale or LC_NUMERIC) |
| 223 |
|
| 224 |
# Qualify the numerator and denominator units. This will turn possibly partial |
| 225 |
# units like "kilometer" or "hour" into actual units like "length-kilometer" and |
| 226 |
# "duration-hour". |
| 227 |
|
| 228 |
resolved_numerator_unit = _find_unit_pattern(numerator_unit, locale=locale) |
| 229 |
resolved_denominator_unit = _find_unit_pattern(denominator_unit, locale=locale) |
| 230 |
|
| 231 |
# If either was not found, we can't possibly build a suitable compound unit either. |
| 232 |
if not (resolved_numerator_unit and resolved_denominator_unit): |
| 233 |
return None |
| 234 |
|
| 235 |
# Since compound units are named "speed-kilometer-per-hour", we'll have to slice off |
| 236 |
# the quantities (i.e. "length", "duration") from both qualified units. |
| 237 |
|
| 238 |
bare_numerator_unit = resolved_numerator_unit.split("-", 1)[-1] |
| 239 |
bare_denominator_unit = resolved_denominator_unit.split("-", 1)[-1] |
| 240 |
|
| 241 |
# Now we can try and rebuild a compound unit specifier, then qualify it: |
| 242 |
|
| 243 |
return _find_unit_pattern( |
| 244 |
f"{bare_numerator_unit}-per-{bare_denominator_unit}", |
| 245 |
locale=locale, |
| 246 |
) |
| 247 |
|
| 248 |
|
| 249 |
def format_compound_unit( |
| 250 |
numerator_value: str | float | decimal.Decimal, |
| 251 |
numerator_unit: str | None = None, |
| 252 |
denominator_value: str | float | decimal.Decimal = 1, |
| 253 |
denominator_unit: str | None = None, |
| 254 |
length: Literal["short", "long", "narrow"] = "long", |
| 255 |
format: str | None = None, |
| 256 |
locale: Locale | str | None = None, |
| 257 |
*, |
| 258 |
numbering_system: Literal["default"] | str = "latn", |
| 259 |
) -> str | None: |
| 260 |
""" |
| 261 |
Format a compound number value, i.e. "kilometers per hour" or similar. |
| 262 |
|
| 263 |
Both unit specifiers are optional to allow for formatting of arbitrary values still according |
| 264 |
to the locale's general "per" formatting specifier. |
| 265 |
|
| 266 |
>>> format_compound_unit(7, denominator_value=11, length="short", locale="pt") |
| 267 |
'7/11' |
| 268 |
|
| 269 |
>>> format_compound_unit(150, "kilometer", denominator_unit="hour", locale="sv") |
| 270 |
'150 kilometer per timme' |
| 271 |
|
| 272 |
>>> format_compound_unit(150, "kilowatt", denominator_unit="year", locale="fi") |
| 273 |
'150 kilowattia / vuosi' |
| 274 |
|
| 275 |
>>> format_compound_unit(32.5, "ton", 15, denominator_unit="hour", locale="en") |
| 276 |
'32.5 tons per 15 hours' |
| 277 |
|
| 278 |
>>> format_compound_unit(1234.5, "ton", 15, denominator_unit="hour", locale="ar_EG", numbering_system="arab") |
| 279 |
'1٬234٫5 طن لكل 15 ساعة' |
| 280 |
|
| 281 |
>>> format_compound_unit(160, denominator_unit="square-meter", locale="fr") |
| 282 |
'160 par m\\xe8tre carr\\xe9' |
| 283 |
|
| 284 |
>>> format_compound_unit(4, "meter", "ratakisko", length="short", locale="fi") |
| 285 |
'4 m/ratakisko' |
| 286 |
|
| 287 |
>>> format_compound_unit(35, "minute", denominator_unit="nautical-mile", locale="sv") |
| 288 |
'35 minuter per nautisk mil' |
| 289 |
|
| 290 |
>>> from babel.numbers import format_currency |
| 291 |
>>> format_compound_unit(format_currency(35, "JPY", locale="de"), denominator_unit="liter", locale="de") |
| 292 |
'35\\xa0\\xa5 pro Liter' |
| 293 |
|
| 294 |
See https://www.unicode.org/reports/tr35/tr35-general.html#perUnitPatterns |
| 295 |
|
| 296 |
:param numerator_value: The numerator value. This may be a string, |
| 297 |
in which case it is considered preformatted and the unit is ignored. |
| 298 |
:param numerator_unit: The numerator unit. See `format_unit`. |
| 299 |
:param denominator_value: The denominator value. This may be a string, |
| 300 |
in which case it is considered preformatted and the unit is ignored. |
| 301 |
:param denominator_unit: The denominator unit. See `format_unit`. |
| 302 |
:param length: The formatting length. "short", "long" or "narrow" |
| 303 |
:param format: An optional format, as accepted by `format_decimal`. |
| 304 |
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale. |
| 305 |
:param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn". |
| 306 |
The special value "default" will use the default numbering system of the locale. |
| 307 |
:return: A formatted compound value. |
| 308 |
:raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale. |
| 309 |
""" |
| 310 |
locale = Locale.parse(locale or LC_NUMERIC) |
| 311 |
|
| 312 |
# Look for a specific compound unit first... |
| 313 |
|
| 314 |
if numerator_unit and denominator_unit and denominator_value == 1: |
| 315 |
compound_unit = _find_compound_unit(numerator_unit, denominator_unit, locale=locale) |
| 316 |
if compound_unit: |
| 317 |
return format_unit( |
| 318 |
numerator_value, |
| 319 |
compound_unit, |
| 320 |
length=length, |
| 321 |
format=format, |
| 322 |
locale=locale, |
| 323 |
numbering_system=numbering_system, |
| 324 |
) |
| 325 |
|
| 326 |
# ... failing that, construct one "by hand". |
| 327 |
|
| 328 |
if isinstance(numerator_value, str): # Numerator is preformatted |
| 329 |
formatted_numerator = numerator_value |
| 330 |
elif numerator_unit: # Numerator has unit |
| 331 |
formatted_numerator = format_unit( |
| 332 |
numerator_value, |
| 333 |
numerator_unit, |
| 334 |
length=length, |
| 335 |
format=format, |
| 336 |
locale=locale, |
| 337 |
numbering_system=numbering_system, |
| 338 |
) |
| 339 |
else: # Unitless numerator |
| 340 |
formatted_numerator = format_decimal( |
| 341 |
numerator_value, |
| 342 |
format=format, |
| 343 |
locale=locale, |
| 344 |
numbering_system=numbering_system, |
| 345 |
) |
| 346 |
|
| 347 |
if isinstance(denominator_value, str): # Denominator is preformatted |
| 348 |
formatted_denominator = denominator_value |
| 349 |
elif denominator_unit: # Denominator has unit |
| 350 |
if denominator_value == 1: # support perUnitPatterns when the denominator is 1 |
| 351 |
denominator_unit = _find_unit_pattern(denominator_unit, locale=locale) |
| 352 |
per_pattern = ( |
| 353 |
locale._data["unit_patterns"] |
| 354 |
.get(denominator_unit, {}) |
| 355 |
.get(length, {}) |
| 356 |
.get("per") |
| 357 |
) |
| 358 |
if per_pattern: |
| 359 |
return per_pattern.format(formatted_numerator) |
| 360 |
# See TR-35's per-unit pattern algorithm, point 3.2. |
| 361 |
# For denominator 1, we replace the value to be formatted with the empty string; |
| 362 |
# this will make `format_unit` return " second" instead of "1 second". |
| 363 |
denominator_value = "" |
| 364 |
|
| 365 |
formatted_denominator = format_unit( |
| 366 |
denominator_value, |
| 367 |
measurement_unit=(denominator_unit or ""), |
| 368 |
length=length, |
| 369 |
format=format, |
| 370 |
locale=locale, |
| 371 |
numbering_system=numbering_system, |
| 372 |
).strip() |
| 373 |
else: # Bare denominator |
| 374 |
formatted_denominator = format_decimal( |
| 375 |
denominator_value, |
| 376 |
format=format, |
| 377 |
locale=locale, |
| 378 |
numbering_system=numbering_system, |
| 379 |
) |
| 380 |
|
| 381 |
# TODO: this doesn't support "compound_variations" (or "prefix"), and will fall back to the "x/y" representation |
| 382 |
per_pattern = ( |
| 383 |
locale._data["compound_unit_patterns"] |
| 384 |
.get("per", {}) |
| 385 |
.get(length, {}) |
| 386 |
.get("compound", "{0}/{1}") |
| 387 |
) |
| 388 |
|
| 389 |
return per_pattern.format(formatted_numerator, formatted_denominator) |