Skip to content

FURB101 and FURB103 shouldn’t apply when the I/O variable is used later #21483

@dscorbett

Description

@dscorbett

Summary

read-whole-file (FURB101) and write-whole-file (FURB103) should be suppressed when the I/O variable is used after the with block (unless the variable is unconditionally rebound). There is no straightforward way to get the same behavior by using the suggested pathlib methods. Examples:

$ cat >furb10.py <<'# EOF'
with open("furb10.py", encoding="utf-8") as f1:
    _ = f1.read()
try:
    print(f1.mode)
except NameError as e:
    print(e)

with open("furb10.txt", "w") as f2:
    f2.write("\n")
try:
    print(f2.encoding)
except NameError as e:
    print(e)
# EOF

$ python furb10.py
r
UTF-8

$ ruff --isolated check furb10.py --select FURB101,FURB103 --preview --fix
Found 2 errors (2 fixed, 0 remaining).

$ cat furb10.py
import pathlib
_ = pathlib.Path("furb10.py").read_text(encoding="utf-8")
try:
    print(f1.mode)
except NameError as e:
    print(e)

pathlib.Path("furb10.txt").write_text("\n")
try:
    print(f2.encoding)
except NameError as e:
    print(e)

$ python furb10.py
name 'f1' is not defined
name 'f2' is not defined

Version

ruff 0.14.5 (87dafb8 2025-11-13)

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions