Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/black/numerics.py: 19%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

36 statements  

1""" 

2Formatting numeric literals. 

3""" 

4 

5from blib2to3.pytree import Leaf 

6 

7 

8def format_hex(text: str) -> str: 

9 """ 

10 Formats a hexadecimal string like "0x12B3" 

11 """ 

12 before, after = text[:2], text[2:] 

13 return f"{before}{after.upper()}" 

14 

15 

16def format_scientific_notation(text: str) -> str: 

17 """Formats a numeric string utilizing scientific notation""" 

18 before, after = text.split("e") 

19 sign = "" 

20 if after.startswith("-"): 

21 after = after[1:] 

22 sign = "-" 

23 elif after.startswith("+"): 

24 after = after[1:] 

25 before = format_float_or_int_string(before) 

26 return f"{before}e{sign}{after}" 

27 

28 

29def format_complex_number(text: str) -> str: 

30 """Formats a complex string like `10j`""" 

31 number = text[:-1] 

32 suffix = text[-1] 

33 return f"{format_float_or_int_string(number)}{suffix}" 

34 

35 

36def format_float_or_int_string(text: str) -> str: 

37 """Formats a float string like "1.0".""" 

38 if "." not in text: 

39 return text 

40 

41 before, after = text.split(".") 

42 return f"{before or 0}.{after or 0}" 

43 

44 

45def normalize_numeric_literal(leaf: Leaf) -> None: 

46 """Normalizes numeric (float, int, and complex) literals. 

47 

48 All letters used in the representation are normalized to lowercase.""" 

49 text = leaf.value.lower() 

50 if text.startswith(("0o", "0b")): 

51 # Leave octal and binary literals alone. 

52 pass 

53 elif text.startswith("0x"): 

54 text = format_hex(text) 

55 elif "e" in text: 

56 text = format_scientific_notation(text) 

57 elif text.endswith("j"): 

58 text = format_complex_number(text) 

59 else: 

60 text = format_float_or_int_string(text) 

61 leaf.value = text