astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
32.59k stars 1.09k forks source link

rule for ValueError: I/O operation on closed file. #10517

Open tooptoop4 opened 7 months ago

tooptoop4 commented 7 months ago

ruff does not complain about:

with open('/a.txt', "w") as f:
    f.write('a')
with open('/b.txt', "w"):
    f.write('b')

but python does:

ValueError: I/O operation on closed file.
MichaReiser commented 7 months ago

Do you think the rule could be generalized to disallow method calls on any object defined in a context expression after the with statement?

zanieb commented 7 months ago

@MichaReiser no, you can safely use many objects after their context is exited :) we'd need type-inference for that to be broadly correct.

autinerd commented 7 months ago

For example with with pytest.raises() as exc_info you have to use the object after the context is exited.

charliermarsh commented 7 months ago

We would probably need to make this specific to open calls (which would be okay).

tooptoop4 commented 7 months ago

https://github.com/wemake-services/wemake-python-styleguide?tab=readme-ov-file finds this

flake8 --select WPS441 somefile.py

https://wemake-python-styleguide.readthedocs.io/en/0.16.1/pages/usage/violations/best_practices.html#wemake_python_styleguide.violations.best_practices.ControlVarUsedAfterBlockViolation