Skip to content

Commit 92ac622

Browse files
committed
Correctecly handle single-element tuples in yapf nested fixup.
1 parent 04d9c37 commit 92ac622

File tree

2 files changed

+18
-16
lines changed

2 files changed

+18
-16
lines changed

formate/__init__.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
#
2828

2929
# stdlib
30+
import re
3031
from configparser import ConfigParser
3132
from typing import Iterable, Mapping, Optional, Sequence
3233

@@ -170,6 +171,10 @@ def isort_hook(
170171
return source
171172

172173

174+
# e.g. " ), )" or " )))), )"
175+
yapf_nested_fixup_pattern = re.compile(r"([ \t])([)}\]]?)([)}\]], )([)}\]])")
176+
177+
173178
@wants_global_config
174179
def yapf_hook(source: str, formate_global_config: Optional[Mapping] = None, **kwargs) -> str:
175180
r"""
@@ -227,22 +232,14 @@ def yapf_hook(source: str, formate_global_config: Optional[Mapping] = None, **kw
227232
reformatted_code: str = FormatTree(tree, style_config=str(config_file))
228233

229234
# Yapf can collapse nested calls onto one line but does nothing about the commas.
230-
# TODO: more performant, with re.sub?
231-
for bad_pattern, good_pattern in [
232-
("), )", "))"),
233-
("), }", ")}"),
234-
("), ]", ")]"),
235-
236-
("], )", "])"),
237-
("], }", "]}"),
238-
("], ]", "]]"),
239-
240-
("}, )", "})"),
241-
("}, }", "}}"),
242-
("}, ]", "}]"),
243-
]:
244-
245-
while bad_pattern in reformatted_code:
235+
while True:
236+
matches = yapf_nested_fixup_pattern.findall(reformatted_code)
237+
if not matches:
238+
break
239+
240+
for match in matches:
241+
bad_pattern = match[0] + match[1] + match[2] + match[3]
242+
good_pattern = match[0] + match[1] + match[2][0] + match[3]
246243
reformatted_code = reformatted_code.replace(bad_pattern, good_pattern)
247244

248245
return reformatted_code

tests/test_yapf_nested_fixups.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,8 @@ def foo():
3232
advanced_file_regression.check(
3333
yapf_hook(src, yapf_style=PathPlus(__file__).parent.parent.joinpath(".style.yapf").as_posix()),
3434
)
35+
36+
37+
def test_tuple():
38+
src = 'top_tmp["normalized"] = top_tmp.apply(normalize, args=(max(top_tmp["intensity"]), ), axis=1)\n'
39+
assert yapf_hook(src, yapf_style=PathPlus(__file__).parent.parent.joinpath(".style.yapf").as_posix()) == src

0 commit comments

Comments
 (0)