Skip to content

Commit

Permalink
Don't emit B009/B010 for keywords (#117)
Browse files Browse the repository at this point in the history
because using normal attribute access would be a SyntaxError.
  • Loading branch information
Zac-HD committed Feb 1, 2020
1 parent e233647 commit 891fc92
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
3 changes: 3 additions & 0 deletions bugbear.py
Expand Up @@ -4,6 +4,7 @@
from contextlib import suppress
from functools import lru_cache, partial
import itertools
from keyword import iskeyword
import logging
import re

Expand Down Expand Up @@ -225,12 +226,14 @@ def visit_Call(self, node):
node.func.id == "getattr"
and len(node.args) == 2 # noqa: W503
and _is_identifier(node.args[1]) # noqa: W503
and not iskeyword(node.args[1].s) # noqa: W503
):
self.errors.append(B009(node.lineno, node.col_offset))
elif (
node.func.id == "setattr"
and len(node.args) == 3 # noqa: W503
and _is_identifier(node.args[1]) # noqa: W503
and not iskeyword(node.args[1].s) # noqa: W503
):
self.errors.append(B010(node.lineno, node.col_offset))

Expand Down
6 changes: 4 additions & 2 deletions tests/b009_b010.py
@@ -1,7 +1,7 @@
"""
Should emit:
B009 - Line 16, 17, 18
B010 - Line 26, 27, 28
B009 - Line 17, 18, 19
B010 - Line 28, 29, 30
"""

# Valid getattr usage
Expand All @@ -11,6 +11,7 @@
getattr(foo, "bar{foo}".format(foo="a"))
getattr(foo, bar, None)
getattr(foo, "123abc")
getattr(foo, "except")

# Invalid usage
getattr(foo, "bar")
Expand All @@ -21,6 +22,7 @@
setattr(foo, bar, None)
setattr(foo, "bar{foo}".format(foo="a"), None)
setattr(foo, "123abc", None)
getattr(foo, "except", None)

# Invalid usage
setattr(foo, "bar", None)
Expand Down
6 changes: 3 additions & 3 deletions tests/test_bugbear.py
Expand Up @@ -124,12 +124,12 @@ def test_b009_b010(self):
bbc = BugBearChecker(filename=str(filename))
errors = list(bbc.run())
all_errors = [
B009(16, 0),
B009(17, 0),
B009(18, 0),
B010(26, 0),
B010(27, 0),
B009(19, 0),
B010(28, 0),
B010(29, 0),
B010(30, 0),
]
self.assertEqual(errors, self.errors(*all_errors))

Expand Down

0 comments on commit 891fc92

Please sign in to comment.