diff --git a/bugbear.py b/bugbear.py index 5feea55..621bc3d 100644 --- a/bugbear.py +++ b/bugbear.py @@ -4,6 +4,7 @@ from contextlib import suppress from functools import lru_cache, partial import itertools +from keyword import iskeyword import logging import re @@ -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)) diff --git a/tests/b009_b010.py b/tests/b009_b010.py index f37a47a..0df080d 100644 --- a/tests/b009_b010.py +++ b/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 @@ -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") @@ -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) diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py index 006eabc..bc4c61a 100644 --- a/tests/test_bugbear.py +++ b/tests/test_bugbear.py @@ -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))