Repository: wemake-services/wemake-python-styleguide

Issue:
WPS426 triggers on safe lambdas
# Bug report

<!--
Hi, thanks for submitting a bug. We appreciate that.

But, we will need some information about what's wrong to help you.
-->

## What's wrong

<!-- Describe what is not working. Please, attach a traceback. -->

```python
def _show_titles(number_of_posts: int) -> Sequence[FutureResultE[str]]:
    return [
        # Notice how easily we compose async and sync functions:
        _fetch_post(post_id).map(lambda post: post['title'])
        # TODO: try `for post_id in (2, 1, 0):` to see how async errors work
        for post_id in range(1, number_of_posts + 1)
    ]
```

Raises:

```
  32:9     WPS426 Found `lambda` in loop's body
  _fetch_post(post_id).map(lambda post: post['title'])
  ^
```

But it should not!

## How is that should be

Why? Because this `lambda` does not use `post_id` in its body. It is safe to be used.
So, if `lambda` uses only its args - we can allow it.

<!-- Describe how it should work. -->

<!--

  Love wemake-python-styleguide? ❤️
  Do you want your bugs to be solved faster?

  Please consider supporting our collective:
👉  https://opencollective.com/wemake-python-styleguide/donate

-->

## System information

### flake8 information

Contents of `flake8 --bug-report`:

### pip information

Contents of `pip freeze`:

WPS426 triggers on safe lambdas
# Bug report

<!--
Hi, thanks for submitting a bug. We appreciate that.

But, we will need some information about what's wrong to help you.
-->

## What's wrong

<!-- Describe what is not working. Please, attach a traceback. -->

```python
def _show_titles(number_of_posts: int) -> Sequence[FutureResultE[str]]:
    return [
        # Notice how easily we compose async and sync functions:
        _fetch_post(post_id).map(lambda post: post['title'])
        # TODO: try `for post_id in (2, 1, 0):` to see how async errors work
        for post_id in range(1, number_of_posts + 1)
    ]
```

Raises:

```
  32:9     WPS426 Found `lambda` in loop's body
  _fetch_post(post_id).map(lambda post: post['title'])
  ^
```

But it should not!

## How is that should be

Why? Because this `lambda` does not use `post_id` in its body. It is safe to be used.
So, if `lambda` uses only its args - we can allow it.

<!-- Describe how it should work. -->

<!--

  Love wemake-python-styleguide? ❤️
  Do you want your bugs to be solved faster?

  Please consider supporting our collective:
👉  https://opencollective.com/wemake-python-styleguide/donate

-->

## System information

### flake8 information

Contents of `flake8 --bug-report`:

### pip information

Contents of `pip freeze`:



Discussion:
@sobolevn I would love to work on it, I but would need some guidance. Currently going through this [guide](https://wemake-python-stylegui.de/en/latest/pages/api/contributing.html#tutorials). If there is something else I need to know beforehand, do let me know.
@HeroicHitesh you are more than welcome! You would need to implement a fix to our `ast` visitor. 
It should not be hard. 

I would probaly start with a failing test. 
I'd like to pick this up, but I think some of the tests are in contradiction to this.

> if lambda uses only its args - we can allow it.

**These lambda functions use only their args but are considered wrong:**
https://github.com/wemake-services/wemake-python-styleguide/blob/ece40b94d7649cc30a3e8a896513719d28099aed/tests/test_visitors/test_ast/test_loops/test_loops/test_lambda_in_loop.py#L45

https://github.com/wemake-services/wemake-python-styleguide/blob/ece40b94d7649cc30a3e8a896513719d28099aed/tests/test_visitors/test_ast/test_loops/test_loops/test_lambda_in_loop.py#L50

https://github.com/wemake-services/wemake-python-styleguide/blob/ece40b94d7649cc30a3e8a896513719d28099aed/tests/test_visitors/test_ast/test_loops/test_loops/test_lambda_in_loop.py#L55

https://github.com/wemake-services/wemake-python-styleguide/blob/ece40b94d7649cc30a3e8a896513719d28099aed/tests/test_visitors/test_ast/test_loops/test_loops/test_lambda_in_loop.py#L27

**On the other hand, this lambda function uses a variable outside its scope and is considered correct:**
https://github.com/wemake-services/wemake-python-styleguide/blob/ece40b94d7649cc30a3e8a896513719d28099aed/tests/test_visitors/test_ast/test_loops/test_loops/test_lambda_in_loop.py#L83

Happy for me to change these tests when I implement the fix?
Yes, these tests should be changed! It was a bad idea to forbid all lambdas in a for loop for someone who loves functional programming 😆 

Please, feel free to change anything that is related to this task.

And thanks a lot for your help! 👍 
@sobolevn I would love to work on it, I but would need some guidance. Currently going through this [guide](https://wemake-python-stylegui.de/en/latest/pages/api/contributing.html#tutorials). If there is something else I need to know beforehand, do let me know.
@HeroicHitesh you are more than welcome! You would need to implement a fix to our `ast` visitor. 
It should not be hard. 

I would probaly start with a failing test. 
I'd like to pick this up, but I think some of the tests are in contradiction to this.

> if lambda uses only its args - we can allow it.

**These lambda functions use only their args but are considered wrong:**
https://github.com/wemake-services/wemake-python-styleguide/blob/ece40b94d7649cc30a3e8a896513719d28099aed/tests/test_visitors/test_ast/test_loops/test_loops/test_lambda_in_loop.py#L45

https://github.com/wemake-services/wemake-python-styleguide/blob/ece40b94d7649cc30a3e8a896513719d28099aed/tests/test_visitors/test_ast/test_loops/test_loops/test_lambda_in_loop.py#L50

https://github.com/wemake-services/wemake-python-styleguide/blob/ece40b94d7649cc30a3e8a896513719d28099aed/tests/test_visitors/test_ast/test_loops/test_loops/test_lambda_in_loop.py#L55

https://github.com/wemake-services/wemake-python-styleguide/blob/ece40b94d7649cc30a3e8a896513719d28099aed/tests/test_visitors/test_ast/test_loops/test_loops/test_lambda_in_loop.py#L27

**On the other hand, this lambda function uses a variable outside its scope and is considered correct:**
https://github.com/wemake-services/wemake-python-styleguide/blob/ece40b94d7649cc30a3e8a896513719d28099aed/tests/test_visitors/test_ast/test_loops/test_loops/test_lambda_in_loop.py#L83

Happy for me to change these tests when I implement the fix?
Yes, these tests should be changed! It was a bad idea to forbid all lambdas in a for loop for someone who loves functional programming 😆 

Please, feel free to change anything that is related to this task.

And thanks a lot for your help! 👍 

Resolving patch:
diff --git a/wemake_python_styleguide/visitors/ast/loops.py b/wemake_python_styleguide/visitors/ast/loops.py
--- a/wemake_python_styleguide/visitors/ast/loops.py
+++ b/wemake_python_styleguide/visitors/ast/loops.py
@@ -177,15 +177,17 @@ def _check_lambda_inside_loop(
         self,
         node: Union[AnyLoop, AnyComprehension],
     ) -> None:
-        container_names = self._containers.get(type(node), ())
-        for container in container_names:
-            body = getattr(node, container, [])
-            if not isinstance(body, list):
-                body = [body]
-
-            for subnode in body:
-                if walk.is_contained(subnode, ast.Lambda):
-                    self.add_violation(LambdaInsideLoopViolation(node))
+        for lambda_node in walk.get_subnodes_by_type(node, ast.Lambda):
+            arguments = (
+                arg.arg for arg
+                in walk.get_subnodes_by_type(lambda_node, ast.arg)
+            )
+            body = (
+                subnode.id for subnode
+                in walk.get_subnodes_by_type(lambda_node.body, ast.Name)
+            )
+            if not all(symbol in arguments for symbol in body):
+                self.add_violation(LambdaInsideLoopViolation(node))
 
     def _check_useless_continue(self, node: AnyLoop) -> None:
         nodes_at_line: DefaultDict[int, List[ast.AST]] = defaultdict(list)


Test patch:
diff --git a/tests/test_visitors/test_ast/test_loops/test_loops/test_lambda_in_loop.py b/tests/test_visitors/test_ast/test_loops/test_loops/test_lambda_in_loop.py
--- a/tests/test_visitors/test_ast/test_loops/test_loops/test_lambda_in_loop.py
+++ b/tests/test_visitors/test_ast/test_loops/test_loops/test_lambda_in_loop.py
@@ -17,14 +17,7 @@ def wrapper():
 def wrapper():
     for index in range(10):
         if some:
-            print(lambda: index)
-"""
-
-nested_argument_lambda_inside_for_loop = """
-def wrapper():
-    for index in range(10):
-        if some:
-            print(lambda index=inde: index)
+            print(lambda x: x + index)
 """
 
 lambda_inside_while_loop = """
@@ -42,17 +35,17 @@ def wrapper():
 
 lambda_inside_set = """
 def wrapper():
-    return {lambda x=x: x for x in some()}
+    return {lambda: x for x in some()}
 """
 
 lambda_inside_list = """
 def wrapper():
-    return [lambda x: x for x in some()]
+    return [lambda: x for x in some()]
 """
 
 lambda_inside_gen = """
 def wrapper():
-    return (lambda x: x for x in some())
+    return (lambda: x for x in some())
 """
 
 lambda_inside_dict_key = """
@@ -68,6 +61,12 @@ def wrapper():
 # Correct:
 
 correct_lambda_inside_for = """
+def wrapper():
+    for index in range(10):
+        print(lambda x: x)
+"""
+
+correct_lambda_inside_map = """
 def wrapper():
     for some in map(lambda x: x * 2, items):
         ...
@@ -80,14 +79,20 @@ def wrapper():
 
 correct_lambda_inside_list = """
 def wrapper():
-    return [x for x in some() if callback(lambda: x)]
+    return [x for x in some() if callback(lambda x: x)]
+"""
+
+correct_lambda_nested_argument_for = """
+def wrapper():
+    for index in range(10):
+        if some:
+            print(lambda index=some: index)
 """
 
 
 @pytest.mark.parametrize('code', [
     lambda_inside_for_loop,
     nested_lambda_inside_for_loop,
-    nested_argument_lambda_inside_for_loop,
     lambda_inside_while_loop,
     nested_lambda_inside_while_loop,
     lambda_inside_list,
@@ -114,8 +119,10 @@ def test_lambda_body(
 
 @pytest.mark.parametrize('code', [
     correct_lambda_inside_for,
+    correct_lambda_inside_map,
     correct_lambda_inside_list,
     correct_lambda_inside_set,
+    correct_lambda_nested_argument_for,
 ])
 def test_correct_lambda_body(
     assert_errors,