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

Add C420 rule #522

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Add C420 rule #522

wants to merge 1 commit into from

Conversation

oliver-sanders
Copy link

@oliver-sanders oliver-sanders commented Aug 4, 2023

For discussion...

Add a rule to recommend using generator expressions rather than list comprehensions when they are only used for iteration by a for loop e.g:

- for x in [func(y) for y in iterable]:
+ for x in (func(y) for y in iterable):
    ...

This is an inefficient pattern which seems to crop up every now and again.

The logic for this is similar to C419:

  • List comprehensions prevent short-circuiting e.g:
    for x in [func(y) for y in iterable]:
        if x == 42:
           break  # we didn't need to call `func(y)` for items past this point
        do_something(x)
  • List comprehensions create an intermediate list object, e.g. if iterable is 1'000 items long, then a 1'000 item list will be created in order for the for loop to iterate over which is inefficient.

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.

None yet

1 participant