]> git.madduck.net Git - etc/vim.git/blob - src/black/numerics.py

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

Document black-jupyter hook (#3650)
[etc/vim.git] / src / black / numerics.py
1 """
2 Formatting numeric literals.
3 """
4 from blib2to3.pytree import Leaf
5
6
7 def format_hex(text: str) -> str:
8     """
9     Formats a hexadecimal string like "0x12B3"
10     """
11     before, after = text[:2], text[2:]
12     return f"{before}{after.upper()}"
13
14
15 def format_scientific_notation(text: str) -> str:
16     """Formats a numeric string utilizing scentific notation"""
17     before, after = text.split("e")
18     sign = ""
19     if after.startswith("-"):
20         after = after[1:]
21         sign = "-"
22     elif after.startswith("+"):
23         after = after[1:]
24     before = format_float_or_int_string(before)
25     return f"{before}e{sign}{after}"
26
27
28 def format_complex_number(text: str) -> str:
29     """Formats a complex string like `10j`"""
30     number = text[:-1]
31     suffix = text[-1]
32     return f"{format_float_or_int_string(number)}{suffix}"
33
34
35 def format_float_or_int_string(text: str) -> str:
36     """Formats a float string like "1.0"."""
37     if "." not in text:
38         return text
39
40     before, after = text.split(".")
41     return f"{before or 0}.{after or 0}"
42
43
44 def normalize_numeric_literal(leaf: Leaf) -> None:
45     """Normalizes numeric (float, int, and complex) literals.
46
47     All letters used in the representation are normalized to lowercase."""
48     text = leaf.value.lower()
49     if text.startswith(("0o", "0b")):
50         # Leave octal and binary literals alone.
51         pass
52     elif text.startswith("0x"):
53         text = format_hex(text)
54     elif "e" in text:
55         text = format_scientific_notation(text)
56     elif text.endswith("j"):
57         text = format_complex_number(text)
58     else:
59         text = format_float_or_int_string(text)
60     leaf.value = text