ruff icon indicating copy to clipboard operation
ruff copied to clipboard

improve error message of PERF401 for extends

Open trim21 opened this issue 10 months ago • 5 comments

import os
from pathlib import Path
from typing import Any


directory: Any = []

files: list[Path] = []
for p in directory:
    if p.is_file():
        files.append(p)
    else:
        for dir, _, _files in os.walk(p):
            for _f in _files:
                files.append(Path(dir).joinpath(_f)) # PERF401 Use a list comprehension to create a transformed list

https://play.ruff.rs/cde69c3f-1d15-4089-bb62-5de79566898a

ruff version 0.4.1

(Is this even possible to re-write with list comprehension?)

trim21 avatar Apr 21 '24 07:04 trim21

You can rewrite it like this. Only the inner for loops need to be rewritten.

import os
from pathlib import Path
from typing import Any


directory: Any = []

files: list[Path] = []
for p in directory:
    if p.is_file():
        files.append(p)
    else:
        files.extend(
            Path(dir).joinpath(_f) for dir, _, _files in os.walk(p) for _f in _files
        )

JonathanPlasse avatar Apr 21 '24 12:04 JonathanPlasse

You can rewrite it like this. Only the inner for loops need to be rewritten.

import os
from pathlib import Path
from typing import Any


directory: Any = []

files: list[Path] = []
for p in directory:
    if p.is_file():
        files.append(p)
    else:
        files.extend(
            Path(dir).joinpath(_f) for dir, _, _files in os.walk(p) for _f in _files
        )

so the problem is error message not very clear…

trim21 avatar Apr 21 '24 13:04 trim21

Indeed

JonathanPlasse avatar Apr 21 '24 13:04 JonathanPlasse

I'm not a fan of nested loop in list comprehension repr, I would just disable this rule and leave this issue open...

trim21 avatar Apr 21 '24 13:04 trim21

The documentation does precise that .extend can be used for existing lists.

JonathanPlasse avatar Apr 21 '24 13:04 JonathanPlasse

I think this is actually okay because it is included in the documentation, and it would be hard to know whether or not to recommend this in the error message itself.

charliermarsh avatar May 03 '24 01:05 charliermarsh