Skip to content

Fix ruff rules for comprehensions and performance#981

Open
cclauss wants to merge 1 commit into
pydantic:mainfrom
cclauss:ruff-rules-C4-and-PERF
Open

Fix ruff rules for comprehensions and performance#981
cclauss wants to merge 1 commit into
pydantic:mainfrom
cclauss:ruff-rules-C4-and-PERF

Conversation

@cclauss
Copy link
Copy Markdown
Contributor

@cclauss cclauss commented May 23, 2026

Summary

 [tool.ruff.lint]
- select = ["E", "F", "W", "I", "B", "PIE"]
+ select = ["B", "C4", "E", "F", "I", "PERF", "PIE", "W"]

% ruff check --statistics

4	C416   	unnecessary-comprehension
2	C401   	unnecessary-generator-set
2	PERF203	try-except-in-loop
2	PERF401	manual-list-comprehension
Found 10 errors.
No fixes available (6 hidden fixes can be enabled with the `--unsafe-fixes` option).

https://docs.astral.sh/ruff/rules/#flake8-comprehensions-c4
https://docs.astral.sh/ruff/rules/#perflint-perf

Checklist

  • I understand that this PR may be closed in case there was no previous discussion. (This doesn't apply to typos!)
  • I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • I've updated the documentation accordingly.

% ruff rule PERF401

manual-list-comprehension (PERF401)

Derived from the Perflint linter.

Fix is sometimes available.

What it does

Checks for for loops that can be replaced by a list comprehension.

Why is this bad?

When creating a transformed list from an existing list using a for-loop,
prefer a list comprehension. List comprehensions are more readable and
more performant.

Using the below as an example, the list comprehension is ~10% faster on
Python 3.11, and ~25% faster on Python 3.10.

Note that, as with all perflint rules, this is only intended as a
micro-optimization, and will have a negligible impact on performance in
most cases.

Example

original = list(range(10000))
filtered = []
for i in original:
    if i % 2:
        filtered.append(i)

Use instead:

original = list(range(10000))
filtered = [x for x in original if x % 2]

If you're appending to an existing list, use the extend method instead:

original = list(range(10000))
filtered.extend(x for x in original if x % 2)

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented May 23, 2026

Merging this PR will not alter performance

✅ 7 untouched benchmarks


Comparing cclauss:ruff-rules-C4-and-PERF (2a177ab) with main (72fce81)

Open in CodSpeed

@cclauss cclauss force-pushed the ruff-rules-C4-and-PERF branch from aaf1adc to ff14a7b Compare May 23, 2026 08:48
@cclauss cclauss force-pushed the ruff-rules-C4-and-PERF branch from ff14a7b to 2a177ab Compare May 23, 2026 09:02
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

Successfully merging this pull request may close these issues.

1 participant