-
Notifications
You must be signed in to change notification settings - Fork 95
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
ruff rules for comprehensions and performance #420
Conversation
Thanks, @cclauss! Thinking out loud, we should probably add |
% |
This is ready to merge |
@cclauss could you "squash & merge" (i.e. checking if that works for you or if you're waiting for us :) I would prefer you merging in case you wanted to update the commit message, etc) |
People without permissions need someone to click merge on their behalf. I can do it here once CI passes. |
OK, fixed.
|
https://docs.astral.sh/ruff https://docs.astral.sh/ruff/linter As suggested in #420. Co-authored-by: Aiden Grossman <[email protected]>
%
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 amicro-optimization, and will have a negligible impact on performance in
most cases.
Example
Use instead:
If you're appending to an existing list, use the
extend
method instead:Take care that if the original for-loop uses an assignment expression
as a conditional, such as
if match:=re.match("\d+","123")
, thenthe corresponding comprehension must wrap the assignment
expression in parentheses to avoid a syntax error.