Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

don't rewrite %-format with width+s #529

Merged
merged 1 commit into from Sep 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 3 additions & 2 deletions pyupgrade/_plugins/percent_format.py
Expand Up @@ -128,8 +128,6 @@ def _handle_part(part: PercentFormat) -> str:
if conversion == '%':
return s + '%'
parts = [s, '{']
if width and conversion == 's' and not conversion_flag:
conversion_flag = '>'
if conversion == 's':
conversion = ''
if key:
Expand Down Expand Up @@ -276,6 +274,9 @@ def visit_BinOp(
# no equivalent in format
if conversion in {'a', 'r'} and nontrivial_fmt:
break
# %s with None and width is not supported
if width and conversion == 's':
break
# all dict substitutions must be named
if isinstance(node.right, ast.Dict) and not key:
break
Expand Down
5 changes: 3 additions & 2 deletions tests/features/percent_format_test.py
Expand Up @@ -158,6 +158,7 @@ def test_simplify_conversion_flag(s, expected):
'"%4%" % ()',
# no equivalent in format specifier
'"%.2r" % (1.25)', '"%.2a" % (1.25)',
pytest.param('"%8s" % (None,)', id='unsafe width-string conversion'),
# non-string mod
'i % 3',
# dict format but not keyed arguments
Expand Down Expand Up @@ -208,8 +209,8 @@ def test_percent_format_noop_if_bug_16806():
('"%s" % ("%s" % ("nested",),)', '"{}".format("{}".format("nested"))'),
('"%s%% percent" % (15,)', '"{}% percent".format(15)'),
('"%3f" % (15,)', '"{:3f}".format(15)'),
('"%-5s" % ("hi",)', '"{:<5}".format("hi")'),
('"%9s" % (5,)', '"{:>9}".format(5)'),
('"%-5f" % (5,)', '"{:<5f}".format(5)'),
('"%9f" % (5,)', '"{:9f}".format(5)'),
('"brace {} %s" % (1,)', '"brace {{}} {}".format(1)'),
(
'"%s" % (\n'
Expand Down