ruff
ruff copied to clipboard
improve error message of PERF401 for extends
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?)
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
)
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…
Indeed
I'm not a fan of nested loop in list comprehension repr, I would just disable this rule and leave this issue open...
The documentation does precise that .extend
can be used for existing lists.
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.