Skip to content

Commit 800d347

Browse files
committed
Solve and enforce selected ruff PTH rules
* Use pathlib.Path instead of os.path These changes include only the fixes ruff was able to safely * Unsafe-fixes and some manual changes. * Manual replacement of os.path.join * Enforce passing ruff PTH rules
1 parent e3150e3 commit 800d347

File tree

31 files changed

+157
-154
lines changed

31 files changed

+157
-154
lines changed

pyproject.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ select = [
141141
"PLR",
142142
"PLW",
143143
"PT", # pytest
144+
"PTH",
144145
"PYI", # flake8-pyi
145146
"Q",
146147
"RET", # flake8-return
@@ -164,6 +165,9 @@ ignore = [
164165
"PLR0914", # too-many-local-variables
165166
"PLR0915", # too-many-statements
166167
"PLR2004", # magic-value-comparison
168+
"PTH118", # os-path-join
169+
"PTH208", # os-listdir
170+
"PTH122", # os-path-splitext
167171
]
168172

169173
[tool.ruff.lint.per-file-ignores]

src/semeio/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import argparse
22
import logging
3-
import os
43
import sys
54
from importlib.metadata import PackageNotFoundError, version
5+
from pathlib import Path
66

77
try: # noqa: SIM105
88
__version__ = version(__name__)
@@ -25,6 +25,6 @@
2525

2626

2727
def valid_file(arg):
28-
if os.path.isfile(arg):
28+
if Path(arg).is_file():
2929
return arg
3030
raise argparse.ArgumentTypeError(f"{arg} is not an existing file!")

src/semeio/fmudesign/_excel_to_dict.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def inputdict_to_yaml(inputdict: dict[str, Any], filename: str) -> None:
8383
inputdict (dict)
8484
filename (str): name of output file
8585
"""
86-
with open(filename, "w", encoding="utf-8") as stream:
86+
with Path(filename).open("w", encoding="utf-8") as stream:
8787
yaml.dump(inputdict, stream)
8888

8989

src/semeio/forward_models/design_kw/design_kw.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import logging
2-
import pathlib
32
import re
43
import shlex
54
from collections.abc import Iterable, Mapping, Sequence
5+
from pathlib import Path
66
from re import Match
77
from typing import Any
88

@@ -32,17 +32,17 @@ def run(
3232

3333
valid = True
3434

35-
with open(parameters_file_name, encoding="utf-8") as parameters_file:
35+
with Path(parameters_file_name).open(encoding="utf-8") as parameters_file:
3636
parameters = parameters_file.readlines()
3737

3838
key_vals = extract_key_value(parameters)
3939

4040
key_vals.update(rm_genkw_prefix(key_vals))
4141

42-
with open(template_file_name, encoding="utf-8") as template_file:
42+
with Path(template_file_name).open(encoding="utf-8") as template_file:
4343
template = template_file.readlines()
4444

45-
with open(result_file_name, "w", encoding="utf-8") as result_file:
45+
with Path(result_file_name).open("w", encoding="utf-8") as result_file:
4646
for line in template:
4747
rendered_line = line
4848
if not is_comment(rendered_line):
@@ -55,7 +55,7 @@ def run(
5555
result_file.write(rendered_line)
5656

5757
if valid:
58-
pathlib.Path(_STATUS_FILE_NAME).write_text("DESIGN_KW OK\n", encoding="utf-8")
58+
Path(_STATUS_FILE_NAME).write_text("DESIGN_KW OK\n", encoding="utf-8")
5959

6060
return valid
6161

@@ -202,7 +202,7 @@ def validate_template_keys(
202202
key_vals: Mapping[str, str], template_file_name: str
203203
) -> None:
204204
try:
205-
with open(template_file_name, encoding="utf-8") as template_file:
205+
with Path(template_file_name).open(encoding="utf-8") as template_file:
206206
template = template_file.readlines()
207207
except (OSError, UnicodeDecodeError) as err:
208208
ForwardModelStepWarning.warn(
@@ -225,7 +225,7 @@ def validate_configuration(
225225
template_file_name: str, parameters_file_name: str = "parameters.txt"
226226
) -> None:
227227
try:
228-
with open(parameters_file_name, encoding="utf-8") as parameters_file:
228+
with Path(parameters_file_name).open(encoding="utf-8") as parameters_file:
229229
parameters = parameters_file.readlines()
230230
except (OSError, UnicodeDecodeError) as err:
231231
ForwardModelStepWarning.warn(

src/semeio/forward_models/overburden_timeshift/ots.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232

3333
def ots_load_params(input_file: str) -> OTSConfig:
3434
try:
35-
with open(input_file, encoding="utf-8") as fin:
35+
with Path(input_file).open(encoding="utf-8") as fin:
3636
config = OTSConfig(**yaml.safe_load(fin))
3737
except ValidationError as err:
3838
raise ConfigurationError(
@@ -124,7 +124,7 @@ def ots_run(parameter_file: str) -> None:
124124
+ len(vintage_pairs.ts_rporv)
125125
)
126126
line = "{}, {}, {}" + ", {}" * num_pairs + "\n"
127-
with open(parms.vintages_export_file, "w", encoding="utf-8") as f:
127+
with Path(parms.vintages_export_file).open("w", encoding="utf-8") as f:
128128
for point, (x_index, y_index) in enumerate(
129129
product(
130130
range(1, surface_horizon.get_nx() + 1),

src/semeio/forward_models/rft/gendata_rft.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import logging
33
import os
44
from collections.abc import Mapping, Sequence
5+
from pathlib import Path
56

67
import numpy as np
78
import pandas as pd
@@ -74,7 +75,7 @@ def _write_simdata(
7475
"""Write pressure value, one per line for all points, -1 is used where
7576
there is no pressure information.
7677
"""
77-
with open(output_file, "w+", encoding="utf-8") as file_handle:
78+
with Path(output_file).open("w+", encoding="utf-8") as file_handle:
7879
if dataname in trajectory_df:
7980
file_handle.write(
8081
"\n".join(
@@ -93,7 +94,7 @@ def _write_simdata(
9394

9495
def _write_active(output_file: str, trajectory_df: pd.DataFrame) -> None:
9596
"""Write a file with "1" pr row if a point is active, "0" if not"""
96-
with open(output_file, "w+", encoding="utf-8") as file_handle:
97+
with Path(output_file).open("w+", encoding="utf-8") as file_handle:
9798
file_handle.write(
9899
"\n".join(
99100
trajectory_df.sort_values("order")["is_active"]
@@ -106,7 +107,7 @@ def _write_active(output_file: str, trajectory_df: pd.DataFrame) -> None:
106107

107108
def _write_inactive_info(output_file: str, trajectory_df: pd.DataFrame) -> None:
108109
"""Write a file with explanations to users for inactive points"""
109-
with open(output_file, "w+", encoding="utf-8") as file_handle:
110+
with Path(output_file).open("w+", encoding="utf-8") as file_handle:
110111
if "inactive_info" not in trajectory_df:
111112
file_handle.write("")
112113
else:

src/semeio/forward_models/rft/trajectory.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import os
22
from collections.abc import Iterator
33
from itertools import starmap
4+
from pathlib import Path
45
from typing import Any, Self, TypeAlias
56

67
import pandas as pd
@@ -275,10 +276,10 @@ def load_from_file(cls, filepath: str) -> Self:
275276
trajectory_points: list[Any] = []
276277

277278
filename = os.path.join(filepath)
278-
if not os.path.isfile(filename):
279+
if not Path(filename).is_file():
279280
raise OSError(f"Trajectory file {filename} not found!")
280281

281-
with open(filename, encoding="utf8") as file_handle:
282+
with Path(filename).open(encoding="utf8") as file_handle:
282283
trajectory_lines = file_handle.readlines()
283284

284285
trajectory_lines = [strip_comments(line) for line in trajectory_lines]

src/semeio/forward_models/rft/utility.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import argparse
22
import datetime
3-
import os
43
import warnings
54
from pathlib import Path
65

@@ -13,7 +12,7 @@ def strip_comments(line: str) -> str:
1312

1413

1514
def existing_directory(path: str) -> str:
16-
if not os.path.isdir(path):
15+
if not Path(path).is_dir():
1716
raise argparse.ArgumentTypeError(
1817
f"The path {path} is not an existing directory"
1918
)
@@ -121,7 +120,7 @@ def valid_eclbase(file_path: str) -> tuple[CornerpointGrid, ResdataRFTFile]:
121120
Loads both files with respective loaders and returns them
122121
"""
123122
rft_filepath = file_path + ".RFT"
124-
if not os.path.isfile(rft_filepath):
123+
if not Path(rft_filepath).is_file():
125124
raise argparse.ArgumentTypeError(f"The path {rft_filepath} does not exist")
126125

127126
try:
@@ -134,7 +133,7 @@ def valid_eclbase(file_path: str) -> tuple[CornerpointGrid, ResdataRFTFile]:
134133
) from err
135134

136135
grid_filepath = file_path + ".EGRID"
137-
if not os.path.isfile(grid_filepath):
136+
if not Path(grid_filepath).is_file():
138137
raise argparse.ArgumentTypeError(f"The path {grid_filepath} does not exist")
139138

140139
try:

src/semeio/forward_models/rft/zonemap.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import argparse
2-
import os
32
from collections.abc import Container, Mapping
43
from pathlib import Path
54
from typing import Any, Self
@@ -34,7 +33,7 @@ def load_and_parse_zonemap_file(cls, filename: str) -> Self | None:
3433
if filename == "ZONEMAP_NOT_PROVIDED":
3534
return None
3635

37-
if not os.path.isfile(filename):
36+
if not Path(filename).is_file():
3837
raise argparse.ArgumentTypeError(f"ZoneMap file {filename} not found!")
3938

4039
zones_at_k_value: dict[int, Any] = {}

src/semeio/forward_models/scripts/fm_pyscal.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
import argparse
44
import logging
5-
import os
65
import sys
76
from argparse import ArgumentParser
7+
from pathlib import Path
88
from typing import Literal
99

1010
from pyscal import pyscalcli
@@ -161,7 +161,7 @@ def run(
161161
In contrast with the command line tool where interpolation
162162
parameters are explicit, they are implicit here, and gathered
163163
from parameters.txt"""
164-
if not os.path.exists(relperm_parameters_file):
164+
if not Path(relperm_parameters_file).exists():
165165
_logger.error("%s does not exist", relperm_parameters_file)
166166
sys.exit(1)
167167

@@ -244,9 +244,9 @@ def _get_interpolation_values(
244244
tuple with two values, one for WaterOil and one for GasOil
245245
"""
246246
# Read all key-value pairs from parameters.txt
247-
if not os.path.exists(parameters_file_name):
247+
if not Path(parameters_file_name).exists():
248248
raise FileNotFoundError(f"{parameters_file_name} does not exist")
249-
with open(parameters_file_name, encoding="utf-8") as parameters_file:
249+
with Path(parameters_file_name).open(encoding="utf-8") as parameters_file:
250250
parameters = parameters_file.readlines()
251251
parameter_dict = extract_key_value(parameters)
252252
parameter_dict.update(rm_genkw_prefix(parameter_dict))

0 commit comments

Comments
 (0)