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

Fixed Unnecessary list comprehension #17685

Closed
wants to merge 2 commits into from

Conversation

saippuakauppias
Copy link

➜ ruff check --select=C419
django/forms/formsets.py:388:13: C419 Unnecessary list comprehension
django/forms/formsets.py:579:16: C419 Unnecessary list comprehension
tests/schema/tests.py:304:30: C419 Unnecessary list comprehension
tests/servers/test_basehttp.py:160:17: C419 Unnecessary list comprehension
Found 4 errors.

Rule description: https://docs.astral.sh/ruff/rules/unnecessary-comprehension-any-all/

Why is this bad?

any and all take any iterators, including generators. Converting a generator to a list by way of a list comprehension is unnecessary and reduces performance due to the overhead of creating the list.

For example, compare the performance of all with a list comprehension against that of a generator (~40x faster here):

In [1]: %timeit all([i for i in range(1000)])
8.14 µs ± 25.4 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)

In [2]: %timeit all(i for i in range(1000))
212 ns ± 0.892 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

# List comprehension ensures is_valid() is called for all formsets.
return all([formset.is_valid() for formset in formsets])
# Generator ensures is_valid() is called for all formsets.
return all(formset.is_valid() for formset in formsets)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's not true, you don't put effort to understand the original comment.

@felixxm felixxm closed this Jan 4, 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
2 participants