Skip to content

FURB148 generates invalid fix when arg is a generator #7656

@Skylion007

Description

@Skylion007
a = (b for b in range(1, 100))
for i, _ in enumerate(a):
    print(i)

gets autofixed to:

a = (b for b in range(1, 100))
for i in range(len(a)):
    print(i)

but a is a generator, and len, surprisingly cannot take a generator (len needs a SizedSequence). Running the code in this autofix will generate the following error:

Traceback (most recent call last):
  File "test_file.py", line 2, in <module>
    for i in range(len(a)):
TypeError: object of type 'generator' has no len()

So while this would work if object was a SizedSequence like a tuple, list, dict, or set, it does not work in this case and will generate invalid.

As an aside, using enumerate to generate an index here when it's a generator is rather nifty, not sure there is an easier way to actually get a range length on generator, using enumerate might actually be most efficient in this case.

The command run is ruff test_file.py --select FURB148 --preview --fix
on ruff 0.0.291

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingtype-inferenceRequires more advanced type inference.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions