flake8-comprehensions icon indicating copy to clipboard operation
flake8-comprehensions copied to clipboard

Feature Request: (New Rule) Detect useless generator pattern

Open Skylion007 opened this issue 2 years ago • 1 comments

Description

I just saw this code in the PyTorch codebase and realized that I cannot think of a valid reason to use a generator comprehension like so (either should be removed or replaced with a call to iter).

b = range(1, 10)
print(sorted((a for a in b)))

should either be

print(sorted(iter(b)))

or

print(sorted(b))

Obviously a more specific rule could be added for sorted (since we have a few specific sorted rules anyway), but it would be nice to have this be more generic as the (a for a in b) generator construct doesn't seem particularly useful and just adds an unnecessary context switch of the generator.

Is there a useful situation to use this generator construct? Or should we always flag it?

Skylion007 avatar Apr 30 '23 16:04 Skylion007

This seems like a legitimate rule to add. Would you like to make a PR?

adamchainz avatar May 18 '23 09:05 adamchainz