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

Autofix or better error message/docs for PERF401 + walrus operator #13621

Open
jamesbraza opened this issue Oct 3, 2024 · 2 comments
Open

Autofix or better error message/docs for PERF401 + walrus operator #13621

jamesbraza opened this issue Oct 3, 2024 · 2 comments

Comments

@jamesbraza
Copy link
Contributor

With this code:

my_list = []
for element in my_list:
    if walrus_element := element:
        my_list.append(walrus_element)

ruff==0.6.7's PERF401 errors like so: PERF401 Use a list comprehension to create a transformed list

However, due to the walrus operator (also see #6056), the fix involves putting parenthesis around the walrus.

This is just confusing enough that at first one thinks it's a PERF401 false positive. The request here is to either:

  • Document this special case in the PERF401 docs
  • Emit a special and more specific PERF401 error message when a walrus operator is present
  • Implement an autofix for PERF401 that knows about the parenthesis
@zanieb
Copy link
Member

zanieb commented Oct 4, 2024

There's never an autofix for PERF401 now, right? I'm a bit confused about why this case feels like a false positive, can you share a bit more?

@jamesbraza
Copy link
Contributor Author

Yeah there's no autofix, I was trying to say a possible solution is just doing an autofix.

Does this clarify? It's that what the PERF401 docs suggest in this case is a SyntaxError:

my_list = []
for element in my_list:
    if walrus_element := element:
        my_list.append(walrus_element)

# What ruff's PERF401 docs say, which leads to: SyntaxError: invalid syntax
my_list = [
    walrus_element for element in my_list if walrus_element := element
]

# What you actually need to do is know this parenthesis trick
my_list = [
    walrus_element for element in my_list if (walrus_element := element)
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants