ruff icon indicating copy to clipboard operation
ruff copied to clipboard

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

Open tooptoop4 opened this issue 1 year ago • 5 comments

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.

tooptoop4 avatar Mar 22 '24 05:03 tooptoop4

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

MichaReiser avatar Mar 22 '24 07:03 MichaReiser

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

zanieb avatar Mar 22 '24 20:03 zanieb

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

autinerd avatar Mar 24 '24 07:03 autinerd

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

charliermarsh avatar Mar 24 '24 20:03 charliermarsh

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

tooptoop4 avatar Apr 06 '24 05:04 tooptoop4