Skip to content

Commit

Permalink
Improve B033 (duplicate set items) (#385)
Browse files Browse the repository at this point in the history
- Include the repr() of the duplicate item in the error
- Point the error directly at the duplicate item

Fixes #384
  • Loading branch information
JelleZijlstra committed May 22, 2023
1 parent 27e12af commit a309029
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 16 deletions.
20 changes: 12 additions & 8 deletions bugbear.py
Original file line number Diff line number Diff line change
Expand Up @@ -1351,12 +1351,16 @@ def check_for_b032(self, node):
self.errors.append(B032(node.lineno, node.col_offset))

def check_for_b033(self, node):
constants = [
item.value
for item in filter(lambda x: isinstance(x, ast.Constant), node.elts)
]
if len(constants) != len(set(constants)):
self.errors.append(B033(node.lineno, node.col_offset))
seen = set()
for elt in node.elts:
if not isinstance(elt, ast.Constant):
continue
if elt.value in seen:
self.errors.append(
B033(elt.lineno, elt.col_offset, vars=(repr(elt.value),))
)
else:
seen.add(elt.value)


def compose_call_path(node):
Expand Down Expand Up @@ -1757,8 +1761,8 @@ def visit_Lambda(self, node):

B033 = Error(
message=(
"B033 Sets should not contain duplicate items. Duplicate items will be replaced"
" with a single item at runtime."
"B033 Set should not contain duplicate item {}. Duplicate items will be"
" replaced with a single item at runtime."
)
)

Expand Down
9 changes: 8 additions & 1 deletion tests/b033.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""
Should emit:
B033 - on lines 6-12
B033 - on lines 6-12, 16, 18
"""

test = {1, 2, 3, 3, 5}
Expand All @@ -10,6 +10,13 @@
test = {3, 3.0}
test = {1, True}
test = {0, False}
multi_line = {
"alongvalueeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
1,
True,
0,
False,
}

test = {1, 2, 3, 3.5, 5}
test = {"a", "b", "c", "d", "e"}
Expand Down
16 changes: 9 additions & 7 deletions tests/test_bugbear.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,13 +493,15 @@ def test_b033(self):
bbc = BugBearChecker(filename=str(filename))
errors = list(bbc.run())
expected = self.errors(
B033(6, 7),
B033(7, 7),
B033(8, 7),
B033(9, 7),
B033(10, 7),
B033(11, 7),
B033(12, 7),
B033(6, 17, vars=("3",)),
B033(7, 23, vars=("'c'",)),
B033(8, 21, vars=("True",)),
B033(9, 20, vars=("None",)),
B033(10, 11, vars=("3.0",)),
B033(11, 11, vars=("True",)),
B033(12, 11, vars=("False",)),
B033(16, 4, vars=("True",)),
B033(18, 4, vars=("False",)),
)
self.assertEqual(errors, expected)

Expand Down

0 comments on commit a309029

Please sign in to comment.