Skip to content

Commit d4afd14

Browse files
authored
Fix B010 lambda flase positive (#246)
1 parent e24eb10 commit d4afd14

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

Diff for: bugbear.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,8 @@ def visit_Call(self, node):
326326
):
327327
self.errors.append(B009(node.lineno, node.col_offset))
328328
elif (
329-
node.func.id == "setattr"
329+
not any(isinstance(n, ast.Lambda) for n in self.node_stack)
330+
and node.func.id == "setattr"
330331
and len(node.args) == 3
331332
and _is_identifier(node.args[1])
332333
and not iskeyword(node.args[1].s)

Diff for: tests/b009_b010.py

+18-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""
22
Should emit:
3-
B009 - Line 17, 18, 19
3+
B009 - Line 17, 18, 19, 44
44
B010 - Line 28, 29, 30
55
"""
66

@@ -28,3 +28,20 @@
2828
setattr(foo, "bar", None)
2929
setattr(foo, "_123abc", None)
3030
setattr(foo, "abc123", None)
31+
32+
# Allow use of setattr within lambda expression
33+
# since assignment is not valid in this context.
34+
c = lambda x: setattr(x, "some_attr", 1)
35+
36+
37+
class FakeCookieStore:
38+
def __init__(self, has_setter):
39+
self.cookie_filter = None
40+
if has_setter:
41+
self.setCookieFilter = lambda func: setattr(self, "cookie_filter", func)
42+
43+
44+
# getattr is still flagged within lambda though
45+
c = lambda x: getattr(x, "some_attr")
46+
# should be replaced with
47+
c = lambda x: x.some_attr

Diff for: tests/test_bugbear.py

+1
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,7 @@ def test_b009_b010(self):
169169
B010(28, 0),
170170
B010(29, 0),
171171
B010(30, 0),
172+
B009(45, 14),
172173
]
173174
self.assertEqual(errors, self.errors(*all_errors))
174175

0 commit comments

Comments
 (0)