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

PERF401 is triggered on for-loops that has the walrus operator inside #15047

Closed
Majsvaffla opened this issue Dec 18, 2024 · 3 comments · Fixed by #15050
Closed

PERF401 is triggered on for-loops that has the walrus operator inside #15047

Majsvaffla opened this issue Dec 18, 2024 · 3 comments · Fixed by #15050
Assignees
Labels
bug Something isn't working documentation Improvements or additions to documentation fixes Related to suggested fixes for violations

Comments

@Majsvaffla
Copy link

PERF401 is triggered on code that has the walrus operator inside. The walrus operator is not available in the list-comprehension if-shorthand and it can not be recreated within a single list-comprehension.

Minimal example

items = []

for i in range(5):
    if j := i:
        items.append(j)

This code can obviously be refactored to not include the walrus operator but there are more complex scenarios where it is impossible to do so without using multiple list-comprehensions or duplicating code.

More complex example

import re

items = []

for s in ["abc", "cde", "efg"]:
    if match := re.match(r"e[a-z]+", s):
        items.append(match.group(0))
@AlexWaygood AlexWaygood added the bug Something isn't working label Dec 18, 2024
@AlexWaygood
Copy link
Member

Nice catch. If you use --fix --unsafe-fixes, the autofix also introduces a syntax error, which is very bad...

@AlexWaygood
Copy link
Member

AlexWaygood commented Dec 18, 2024

Although it does work if you parenthesize the walrus:

>>> [i for i in range(5) if (j := i)]
[1, 2, 3, 4]

So maybe the rule is correct in emitting a diagnostic here -- maybe we just need to add a clarification to the docs (that says you'll need to parenthesize the if condition if it has a walrus in it) and make sure the autofix doesn't introduce a syntax error?

@AlexWaygood AlexWaygood added fixes Related to suggested fixes for violations documentation Improvements or additions to documentation labels Dec 18, 2024
@dylwil3 dylwil3 self-assigned this Dec 18, 2024
@Majsvaffla
Copy link
Author

Although it does work if you parenthesize the walrus:

Oh, I didn't realize that but it's obvious now 😄

Then I agree with you that the documentation could include something about it 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working documentation Improvements or additions to documentation fixes Related to suggested fixes for violations
Projects
None yet
3 participants