Skip to content

Commit

Permalink
also fix map in B023. update comments
Browse files Browse the repository at this point in the history
  • Loading branch information
jakkdl committed Oct 26, 2022
1 parent e16ad24 commit f2626f6
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
7 changes: 5 additions & 2 deletions bugbear.py
Expand Up @@ -592,7 +592,7 @@ def check_for_b023(self, loop_node): # noqa: C901
# check for filter&reduce
if (
isinstance(node.func, ast.Name)
and node.func.id in ("filter", "reduce")
and node.func.id in ("filter", "reduce", "map")
) or (
isinstance(node.func, ast.Attribute)
and node.func.attr == "reduce"
Expand All @@ -610,11 +610,14 @@ def check_for_b023(self, loop_node): # noqa: C901
):
safe_functions.append(keyword.value)

# mark `return lambda: x` as safe
# does not (currently) check inner lambdas in a returned expression
# e.g. `return (lambda: x, )
if isinstance(node, ast.Return):
if isinstance(node.value, FUNCTION_NODES):
safe_functions.append(node.value)
# TODO: ast.walk(node) and mark all child nodes safe?

# find unsafe functions
if isinstance(node, FUNCTION_NODES) and node not in safe_functions:
argnames = {
arg.arg for arg in ast.walk(node.args) if isinstance(arg, ast.arg)
Expand Down
10 changes: 9 additions & 1 deletion tests/b023.py
Expand Up @@ -121,6 +121,14 @@ def myfunc(x):
max(range(3), key=lambda y: x * y)
sorted(range(3), key=lambda y: x * y)

any(map(lambda y: x < y, range(3)))
all(map(lambda y: x < y, range(3)))
set(map(lambda y: x < y, range(3)))
list(map(lambda y: x < y, range(3)))
tuple(map(lambda y: x < y, range(3)))
sorted(map(lambda y: x < y, range(3)))
frozenset(map(lambda y: x < y, range(3)))

any(filter(lambda y: x < y, range(3)))
all(filter(lambda y: x < y, range(3)))
set(filter(lambda y: x < y, range(3)))
Expand Down Expand Up @@ -156,7 +164,7 @@ def iter_f(names):
return lambda: name if exists(name) else None

if foo(name):
return [lambda: name] # false alarm, should be fixed?
return [lambda: name] # known false alarm

if False:
return [lambda: i for i in range(3)] # error
4 changes: 2 additions & 2 deletions tests/test_bugbear.py
Expand Up @@ -356,8 +356,8 @@ def test_b023(self):
B023(115, 36, vars=("x",)),
B023(116, 37, vars=("x",)),
B023(117, 36, vars=("x",)),
B023(159, 28, vars=("name",)), # false alarm?
B023(162, 28, vars=("i",)),
B023(167, 28, vars=("name",)), # known false alarm
B023(170, 28, vars=("i",)),
)
self.assertEqual(errors, expected)

Expand Down

0 comments on commit f2626f6

Please sign in to comment.