Skip to content

Commit

Permalink
Convert groups to string to prevent mypy for shouting
Browse files Browse the repository at this point in the history
  • Loading branch information
Shivansh-007 committed Mar 16, 2022
1 parent 2ada012 commit c7fc77c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 12 deletions.
1 change: 0 additions & 1 deletion src/black/linegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,6 @@ def visit_factor(self, node: Node) -> Iterator[Line]:

def visit_STRING(self, leaf: Leaf) -> Iterator[Line]:
if Preview.hex_codes_in_unicode_sequences in self.mode:
# Preview style only
normalize_unicode_escape_sequences(leaf)

if is_docstring(leaf) and "\\\n" not in leaf.value:
Expand Down
23 changes: 12 additions & 11 deletions src/black/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@
FIRST_NON_WHITESPACE_RE: Final = re.compile(r"\s*\t+\s*(\S)")
UNICODE_RE = re.compile(
r"(\\+)("
r"(u([a-zA-Z0-9]{4}))"
r"|(U([a-zA-Z0-9]{0,8}))"
r"|(x([a-zA-Z0-9]{2}))"
r"|(N\{([a-zA-Z0-9]{2})\})"
r"(u([a-zA-Z0-9]{4}))" # Formatting 16-bit unicodes i.e. \uxxxx
r"|(U([a-zA-Z0-9]{0,8}))" # Formatting 32-bit unicodes i.e. \Uxxxxxxxx
r"|(x([a-zA-Z0-9]{2}))" # Formatting unicodes in format of \xhh
r"|(N\{([a-zA-Z0-9]{2})\})" # Formatting named unicodes in format of \N{name}
r")"
)

Expand Down Expand Up @@ -253,23 +253,24 @@ def normalize_unicode_escape_sequences(leaf: Leaf) -> None:
text = leaf.value
prefix = get_string_prefix(text)

def replace(m: Match[AnyStr]) -> AnyStr:
def replace(m: Match[AnyStr]) -> str:
groups = m.groups()
back_slashes = str(groups[0])

if len(groups[0]) % 2 == 0 or prefix == "r":
return groups[0] + groups[1]
if len(back_slashes) % 2 == 0 or prefix == "r":
return back_slashes + str(groups[1])

if groups[2]:
# \u
return groups[0] + "u" + groups[3].lower()
return back_slashes + "u" + str(groups[3].lower())
elif groups[4]:
# \U
return groups[0] + "U" + groups[5].lower()
return back_slashes + "U" + str(groups[5].lower())
elif groups[6]:
# \x
return groups[0] + "x" + groups[7].lower()
return back_slashes + "x" + str(groups[7].lower())
else:
# \N{}
return groups[0] + "N{" + groups[9].upper() + "}"
return back_slashes + "N{" + str(groups[9].upper()) + "}"

leaf.value = re.sub(UNICODE_RE, replace, text)
10 changes: 10 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
x = "\x1f"
x = "\\x1B"
x = "\\\x1b"
x = "\U0001f60e"
x = "\u0001F60E"
x = r"\u0001F60E"
x = "don't format me"
x = "\xa3"
x = "\u2717"
x = "\N{OX}\N{OX}"

0 comments on commit c7fc77c

Please sign in to comment.