From 79311238f16854f0b661f799398bb5cb56d084d9 Mon Sep 17 00:00:00 2001 From: Anthony Sottile Date: Fri, 10 Sep 2021 06:11:36 -0700 Subject: [PATCH] don't rewrite %-format with width+s --- pyupgrade/_plugins/percent_format.py | 5 +++-- tests/features/percent_format_test.py | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/pyupgrade/_plugins/percent_format.py b/pyupgrade/_plugins/percent_format.py index 8dc2c762..1b0599df 100644 --- a/pyupgrade/_plugins/percent_format.py +++ b/pyupgrade/_plugins/percent_format.py @@ -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: @@ -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 diff --git a/tests/features/percent_format_test.py b/tests/features/percent_format_test.py index 57ca3c65..0d620ce0 100644 --- a/tests/features/percent_format_test.py +++ b/tests/features/percent_format_test.py @@ -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 @@ -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'