Skip to content

Commit a309029

Browse files
Improve B033 (duplicate set items) (#385)
- Include the repr() of the duplicate item in the error - Point the error directly at the duplicate item Fixes #384
1 parent 27e12af commit a309029

File tree

3 files changed

+29
-16
lines changed

3 files changed

+29
-16
lines changed

bugbear.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1351,12 +1351,16 @@ def check_for_b032(self, node):
13511351
self.errors.append(B032(node.lineno, node.col_offset))
13521352

13531353
def check_for_b033(self, node):
1354-
constants = [
1355-
item.value
1356-
for item in filter(lambda x: isinstance(x, ast.Constant), node.elts)
1357-
]
1358-
if len(constants) != len(set(constants)):
1359-
self.errors.append(B033(node.lineno, node.col_offset))
1354+
seen = set()
1355+
for elt in node.elts:
1356+
if not isinstance(elt, ast.Constant):
1357+
continue
1358+
if elt.value in seen:
1359+
self.errors.append(
1360+
B033(elt.lineno, elt.col_offset, vars=(repr(elt.value),))
1361+
)
1362+
else:
1363+
seen.add(elt.value)
13601364

13611365

13621366
def compose_call_path(node):
@@ -1757,8 +1761,8 @@ def visit_Lambda(self, node):
17571761

17581762
B033 = Error(
17591763
message=(
1760-
"B033 Sets should not contain duplicate items. Duplicate items will be replaced"
1761-
" with a single item at runtime."
1764+
"B033 Set should not contain duplicate item {}. Duplicate items will be"
1765+
" replaced with a single item at runtime."
17621766
)
17631767
)
17641768

tests/b033.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""
22
Should emit:
3-
B033 - on lines 6-12
3+
B033 - on lines 6-12, 16, 18
44
"""
55

66
test = {1, 2, 3, 3, 5}
@@ -10,6 +10,13 @@
1010
test = {3, 3.0}
1111
test = {1, True}
1212
test = {0, False}
13+
multi_line = {
14+
"alongvalueeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
15+
1,
16+
True,
17+
0,
18+
False,
19+
}
1320

1421
test = {1, 2, 3, 3.5, 5}
1522
test = {"a", "b", "c", "d", "e"}

tests/test_bugbear.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -493,13 +493,15 @@ def test_b033(self):
493493
bbc = BugBearChecker(filename=str(filename))
494494
errors = list(bbc.run())
495495
expected = self.errors(
496-
B033(6, 7),
497-
B033(7, 7),
498-
B033(8, 7),
499-
B033(9, 7),
500-
B033(10, 7),
501-
B033(11, 7),
502-
B033(12, 7),
496+
B033(6, 17, vars=("3",)),
497+
B033(7, 23, vars=("'c'",)),
498+
B033(8, 21, vars=("True",)),
499+
B033(9, 20, vars=("None",)),
500+
B033(10, 11, vars=("3.0",)),
501+
B033(11, 11, vars=("True",)),
502+
B033(12, 11, vars=("False",)),
503+
B033(16, 4, vars=("True",)),
504+
B033(18, 4, vars=("False",)),
503505
)
504506
self.assertEqual(errors, expected)
505507

0 commit comments

Comments
 (0)