]> 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:

Fix test that was not being run (#3939)
[etc/vim.git] / src / black / numerics.py
1 """
2 Formatting numeric literals.
3 """
4
5 from blib2to3.pytree import Leaf
6
7
8 def 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
16 def format_scientific_notation(text: str) -> str:
17     """Formats a numeric string utilizing scentific 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
29 def 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
36 def 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
45 def 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