Skip to content

Commit 09da60c

Browse files
F0RRZZmarat
andauthored
Ignore string literals in f-strings #3548 (#3551)
Co-authored-by: marat <[email protected]>
1 parent 28a6155 commit 09da60c

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ Semantic versioning in our case means:
3030

3131
- Adds `WPS365`: match statement can be simplified to `if`, #3520
3232

33+
### Bugfixes
34+
35+
- Fixes `WPS226` false-positive on fstring parts, #3548
36+
3337

3438
## 1.4.0
3539

tests/test_visitors/test_ast/test_complexity/test_overuses/test_overused_string.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,16 @@ def function() -> Dict[int, {0}]:
9696
...
9797
"""
9898

99+
fstring_same_prefix1 = """
100+
x = f'Hello, {pattern}'
101+
y = f'Hello, {pattern}'
102+
"""
103+
104+
fstring_same_prefix2 = """
105+
x = f'{pattern}-postfix'
106+
y = f'{pattern}-postfix'
107+
"""
108+
99109
EXPECTED_LOCATION = (2, 8)
100110

101111

@@ -257,3 +267,25 @@ def test_common_strings_allowed(
257267
visitor.run()
258268

259269
assert_errors(visitor, [])
270+
271+
272+
@pytest.mark.parametrize(
273+
'strings',
274+
[
275+
fstring_same_prefix1,
276+
fstring_same_prefix2,
277+
],
278+
)
279+
def test_fstring_strings_not_counted(
280+
assert_errors,
281+
parse_ast_tree,
282+
options,
283+
strings,
284+
):
285+
"""Ensures that string literals inside f-strings are not overused."""
286+
tree = parse_ast_tree(strings)
287+
option_values = options(max_string_usages=1)
288+
visitor = StringOveruseVisitor(option_values, tree=tree)
289+
visitor.run()
290+
291+
assert_errors(visitor, [])

wemake_python_styleguide/visitors/ast/complexity/overuses.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,10 @@ def _check_string_constant(self, node: ast.Constant) -> None:
8181
if annotations.is_annotation(node):
8282
return
8383

84+
# Part of the f-string:
85+
if walk.get_closest_parent(node, parents=(ast.JoinedStr,)):
86+
return
87+
8488
# Some strings are so common, that it makes no sense to check if
8589
# they are overused.
8690
if (

0 commit comments

Comments
 (0)