Skip to content

Commit 891fc92

Browse files
authored
Don't emit B009/B010 for keywords (#117)
because using normal attribute access would be a SyntaxError.
1 parent e233647 commit 891fc92

File tree

3 files changed

+10
-5
lines changed

3 files changed

+10
-5
lines changed

bugbear.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from contextlib import suppress
55
from functools import lru_cache, partial
66
import itertools
7+
from keyword import iskeyword
78
import logging
89
import re
910

@@ -225,12 +226,14 @@ def visit_Call(self, node):
225226
node.func.id == "getattr"
226227
and len(node.args) == 2 # noqa: W503
227228
and _is_identifier(node.args[1]) # noqa: W503
229+
and not iskeyword(node.args[1].s) # noqa: W503
228230
):
229231
self.errors.append(B009(node.lineno, node.col_offset))
230232
elif (
231233
node.func.id == "setattr"
232234
and len(node.args) == 3 # noqa: W503
233235
and _is_identifier(node.args[1]) # noqa: W503
236+
and not iskeyword(node.args[1].s) # noqa: W503
234237
):
235238
self.errors.append(B010(node.lineno, node.col_offset))
236239

tests/b009_b010.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""
22
Should emit:
3-
B009 - Line 16, 17, 18
4-
B010 - Line 26, 27, 28
3+
B009 - Line 17, 18, 19
4+
B010 - Line 28, 29, 30
55
"""
66

77
# Valid getattr usage
@@ -11,6 +11,7 @@
1111
getattr(foo, "bar{foo}".format(foo="a"))
1212
getattr(foo, bar, None)
1313
getattr(foo, "123abc")
14+
getattr(foo, "except")
1415

1516
# Invalid usage
1617
getattr(foo, "bar")
@@ -21,6 +22,7 @@
2122
setattr(foo, bar, None)
2223
setattr(foo, "bar{foo}".format(foo="a"), None)
2324
setattr(foo, "123abc", None)
25+
getattr(foo, "except", None)
2426

2527
# Invalid usage
2628
setattr(foo, "bar", None)

tests/test_bugbear.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,12 +124,12 @@ def test_b009_b010(self):
124124
bbc = BugBearChecker(filename=str(filename))
125125
errors = list(bbc.run())
126126
all_errors = [
127-
B009(16, 0),
128127
B009(17, 0),
129128
B009(18, 0),
130-
B010(26, 0),
131-
B010(27, 0),
129+
B009(19, 0),
132130
B010(28, 0),
131+
B010(29, 0),
132+
B010(30, 0),
133133
]
134134
self.assertEqual(errors, self.errors(*all_errors))
135135

0 commit comments

Comments
 (0)