ITADN

`FURB101` and `FURB103` apply safe fixes that cause runtime errors

#26922OpenntBre 创建于 2026-07-16
bugfixespreview
N
ntBrecommented
### Summary After seeing https://github.com/astral-sh/ruff/issues/26920, I found a fix safety issue in FURB101. The rule offers a safe fix: ```console ❯ ruff check --select FURB101 --preview - <<EOF with open(b"file.txt") as f: contents = f.read() EOF error[[FURB101](https://docs.astral.sh/ruff/rules/read-whole-file)][*]: `open` and `read` should be replaced by `Path(b"file.txt").read_text()` --> -:1:6 | 1 | with open(b"file.txt") as f: | ^^^^^^^^^^^^^^^^^^^^^^ 2 | contents = f.read() | help: Replace with `Path(b"file.txt").read_text()` - with open(b"file.txt") as f: - contents = f.read() 1 + import pathlib 2 + contents = pathlib.Path(b"file.txt").read_text() Found 1 error. [*] 1 fixable with the `--fix` option. ``` That causes a runtime error: ```console ❯ uvx python@3.14 <<EOF ∙ /import pathlib contents = pathlib.Path(b"file.txt").read_text() ∙ /EOF Traceback (most recent call last): File "<stdin>", line 2, in <module> File "/opt/homebrew/Cellar/python@3.14/3.14.4_1/Frameworks/Python.framework/Versions/3.14/lib/python3.14/pathlib/__init__.py", line 150, in __init__ raise TypeError( ...<2 lines>... f"not {type(path).__name__!r}") TypeError: argument should be a str or an os.PathLike object where __fspath__ returns a str, not 'bytes' ``` The original code is fine: ```console ❯ uvx python@3.14 <<EOF with open(b"file.txt") as f: contents = f.read() EOF ❯ echo $? 0 ```
1 条评论