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 should not apply to nested list comprehensions #11936

Closed
knyazer opened this issue Jun 19, 2024 · 1 comment
Closed

PERF401 should not apply to nested list comprehensions #11936

knyazer opened this issue Jun 19, 2024 · 1 comment

Comments

@knyazer
Copy link

knyazer commented Jun 19, 2024

Description

PERF401 recommends to use list comprehensions even if it leads to nested list comprehensions. I would guess a lot of people agree that nested list comprehensions are a bad code practice, but I cannot find any sources, sadly.

Minimal example

# test.py
def func():
    mylist = []
    for iterable in [[1], [2], [3]]:
        mylist.append([el + 1 for el in iterable])
    return mylist

When you run ruff check --select PERF401 test.py, you would get a recommendation to use a list comprehension.

While minimal example does not look this bad, here is a real world example:

Real example

times = [
    [transcription.captions[index].end for index in range(len(transcription.captions) - 1)]
    for transcription in [*transcriptionStorage.get(), new_transcription]
    if transcription.isValid()
]

and wow, this is awful!

Possible solution

I'm not sure how ruff internals work, but I guess it should not be extremely hard to figure out that there is a list comprehension inside of the block where the PERF401 is detected.

Other

ruff --version # 0.4.5

@charliermarsh
Copy link
Member

I see the motivation but I feel like this is working as intended. The rule is looking for iterations that could be rewritten as comprehensions for micro-optimization purposes, and it's identifying one here. To take the other side of the argument, it would be surprising for PERF401 to sometimes trigger and sometimes not depending on the target expression. (Candidly, I don't find the real example to be much harder to read, but I recognize that's just subjective).

It's kind of a niche rule -- I'd recommend just disabling it if you're not in a situation that demands it, and aren't happy with the suggestions.

@charliermarsh charliermarsh closed this as not planned Won't fix, can't repro, duplicate, stale Jun 23, 2024
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