Skip to content

Commit e7c04f4

Browse files
maayanmatsliah-techhugovkpre-commit-ci[bot]
authored
Refactor: simplify scientific() and extract _SUPERSCRIPT_MAP constant (#313)
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 55dc47c commit e7c04f4

1 file changed

Lines changed: 16 additions & 21 deletions

File tree

src/humanize/number.py

Lines changed: 16 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,21 @@
1818
NumberOrString: TypeAlias = float | str
1919

2020

21+
_SUPERSCRIPT_MAP = {
22+
"0": "⁰",
23+
"1": "¹",
24+
"2": "²",
25+
"3": "³",
26+
"4": "⁴",
27+
"5": "⁵",
28+
"6": "⁶",
29+
"7": "⁷",
30+
"8": "⁸",
31+
"9": "⁹",
32+
"-": "⁻",
33+
}
34+
35+
2136
def _format_not_finite(value: float) -> str:
2237
"""Utility function to handle infinite and nan cases."""
2338
import math
@@ -415,19 +430,6 @@ def scientific(value: NumberOrString, precision: int = 2) -> str:
415430
"""
416431
import math
417432

418-
exponents = {
419-
"0": "⁰",
420-
"1": "¹",
421-
"2": "²",
422-
"3": "³",
423-
"4": "⁴",
424-
"5": "⁵",
425-
"6": "⁶",
426-
"7": "⁷",
427-
"8": "⁸",
428-
"9": "⁹",
429-
"-": "⁻",
430-
}
431433
try:
432434
value = float(value)
433435
if not math.isfinite(value):
@@ -441,14 +443,7 @@ def scientific(value: NumberOrString, precision: int = 2) -> str:
441443
import re
442444

443445
part2 = re.sub(r"^\+?(\-?)0*(.+)$", r"\1\2", part2)
444-
445-
new_part2 = []
446-
for char in part2:
447-
new_part2.append(exponents[char])
448-
449-
final_str = part1 + " x 10" + "".join(new_part2)
450-
451-
return final_str
446+
return part1 + " x 10" + "".join([_SUPERSCRIPT_MAP[char] for char in part2])
452447

453448

454449
def clamp(

0 commit comments

Comments
 (0)