grass icon indicating copy to clipboard operation
grass copied to clipboard

grass.script.core: Use a context manager for opening files (SIM115) to solve some ResourceWarnings

Open echoix opened this issue 1 year ago • 0 comments

I'm keeping this PR small as grass.script.core is a more commonly used file.

For find_program() and _set_location_description(), a context manager was used directly, as I didn't consider there were better options. In _set_location_description(), I don't understand why the codec module needed to be used to write to a text file, in append mode, in utf-8, instead of a standard open() with encoding set to utf-8, in text mode, and with append

The optional arguments of pathlib.Path().write_text() have the same meaning as in https://docs.python.org/3/library/functions.html#open. At the description of newline argument, they specify that:

When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

This meant that writing the DEFAULT_WIND file in _create_location_xy() can be simplified to a static text write, and can use Path().write_text(). I kept the list of lines for now.

As with other PRs using pathlib to fix SIM115, when changing a function to use pathlib's Path, I change the rest of the function to use the same Path variables and calls. The amount of non-automated changes required for solving the PTH issues https://docs.astral.sh/ruff/rules/#flake8-use-pathlib-pth are too big to do by themselves in a separate PR. So while analyzing the whole function in scope, when possible I apply them.

echoix avatar Oct 20 '24 15:10 echoix