Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

B023 False positive when there is a list comprehension with the same variable name in a loop. #15716

Open
vivodi opened this issue Jan 24, 2025 · 1 comment
Labels
bug Something isn't working

Comments

@vivodi
Copy link

vivodi commented Jan 24, 2025

Description

minimal code snippet:

for _ in range(3):
    [x for x in []]
    def func():
        lambda x: x

command:

ruff check --isolated --select B023 demo.py

log:

demo.py:5:19: B023 Function definition does not bind loop variable `x`
  |
4 |     def func():
5 |         lambda x: x
  |                   ^ B023
  |

Found 1 error.

ruff version: 0.9.2

This is NOT a duplicate of #7847, because x is only used in a list comprehension in the same loop. Ruff should not raise a false positive in this situation.

@orgua
Copy link

orgua commented Feb 28, 2025

I got a similar false positive when variable name is not reused, but pandas.apply() is used:

import pandas as pd

data = pd.DataFrame()
data.loc[0, "hex"] = "72756666"
data.loc[1, "hex"] = "75767576"

def modifier(value):
    return chr(int(value, 16))


for _i in range(0, 4):
    data[f"v{_i}"] = data["hex"].apply(
        lambda x: modifier(x[2 * _i : 2 * _i + 2]),
    )

print(data)

I am pretty sure that the code is correct and it returns what I want:

        hex v0 v1 v2 v3
0  72756666  r  u  f  f
1  75767576  u  v  u  v

but the linting command

ruff check --isolated --select B023 demo.py

triggers

demo.py:13:34: B023 Function definition does not bind loop variable `_i`
   |
11 | for _i in range(0, 4):
12 |     data[f"v{_i}"] = data["hex"].apply(
13 |         lambda x: modifier(x[2 * _i : 2 * _i + 2]),
   |                                  ^^ B023
14 |     )
   |

demo.py:13:43: B023 Function definition does not bind loop variable `_i`
   |
11 | for _i in range(0, 4):
12 |     data[f"v{_i}"] = data["hex"].apply(
13 |         lambda x: modifier(x[2 * _i : 2 * _i + 2]),
   |                                           ^^ B023
14 |     )
   |

Found 2 errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants