ruff rules for comprehensions and performance#420
ruff rules for comprehensions and performance#420boomanaiden154 merged 3 commits intogoogle:mainfrom
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 <aidengrossman@google.com>
%
ruff rule PERF401manual-list-comprehension (PERF401)
Derived from the Perflint linter.
Fix is sometimes available.
What it does
Checks for
forloops 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
perflintrules, 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
extendmethod 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.