Skip to content

Commit dd8e0cd

Browse files
authored
Enable ruff's PTH (flake8-use-pathlib) rules and fix violations (#3129)
1 parent 0cdb87d commit dd8e0cd

16 files changed

+46
-55
lines changed

examples/tutorials/basics/text.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@
7272
fig.coast(land="black", water="skyblue")
7373

7474
# Create space-delimited file
75-
with open("examples.txt", "w") as f:
75+
with Path("examples.txt").open(mode="w") as f:
7676
f.write("114 0.5 0 22p,Helvetica-Bold,white CM BORNEO\n")
7777
f.write("119 3.25 0 12p,Helvetica-Bold,black CM CELEBES SEA\n")
7878
f.write("112 -4.6 0 12p,Helvetica-Bold,black CM JAVA SEA\n")

pygmt/clib/session.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1641,12 +1641,13 @@ def virtualfile_out(
16411641
16421642
Examples
16431643
--------
1644+
>>> from pathlib import Path
16441645
>>> from pygmt.clib import Session
16451646
>>> from pygmt.datatypes import _GMT_DATASET
16461647
>>> from pygmt.helpers import GMTTempFile
16471648
>>>
16481649
>>> with GMTTempFile(suffix=".txt") as tmpfile:
1649-
... with open(tmpfile.name, mode="w") as fp:
1650+
... with Path(tmpfile.name).open(mode="w") as fp:
16501651
... print("1.0 2.0 3.0 TEXT", file=fp)
16511652
...
16521653
... # Create a virtual file for storing the output table.
@@ -1661,8 +1662,7 @@ def virtualfile_out(
16611662
... with lib.virtualfile_out(fname=tmpfile.name) as vouttbl:
16621663
... assert vouttbl == tmpfile.name
16631664
... lib.call_module("read", f"{tmpfile.name} {vouttbl} -Td")
1664-
... with open(vouttbl, mode="r") as fp:
1665-
... line = fp.readline()
1665+
... line = Path(vouttbl).read_text()
16661666
... assert line == "1\t2\t3\tTEXT\n"
16671667
"""
16681668
if fname is not None: # Yield the actual file name.
@@ -1692,13 +1692,14 @@ def read_virtualfile(
16921692
16931693
Examples
16941694
--------
1695+
>>> from pathlib import Path
16951696
>>> from pygmt.clib import Session
16961697
>>> from pygmt.helpers import GMTTempFile
16971698
>>>
16981699
>>> # Read dataset from a virtual file
16991700
>>> with Session() as lib:
17001701
... with GMTTempFile(suffix=".txt") as tmpfile:
1701-
... with open(tmpfile.name, mode="w") as fp:
1702+
... with Path(tmpfile.name).open(mode="w") as fp:
17021703
... print("1.0 2.0 3.0 TEXT", file=fp)
17031704
... with lib.virtualfile_out(kind="dataset") as vouttbl:
17041705
... lib.call_module("read", f"{tmpfile.name} {vouttbl} -Td")
@@ -1779,7 +1780,7 @@ def virtualfile_to_dataset(
17791780
>>>
17801781
>>> with GMTTempFile(suffix=".txt") as tmpfile:
17811782
... # prepare the sample data file
1782-
... with open(tmpfile.name, mode="w") as fp:
1783+
... with Path(tmpfile.name).open(mode="w") as fp:
17831784
... print(">", file=fp)
17841785
... print("1.0 2.0 3.0 TEXT1 TEXT23", file=fp)
17851786
... print("4.0 5.0 6.0 TEXT4 TEXT567", file=fp)

pygmt/datatypes/dataset.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,13 @@ class _GMT_DATASET(ctp.Structure): # noqa: N801
1818
1919
Examples
2020
--------
21+
>>> from pathlib import Path
2122
>>> from pygmt.helpers import GMTTempFile
2223
>>> from pygmt.clib import Session
2324
>>>
2425
>>> with GMTTempFile(suffix=".txt") as tmpfile:
2526
... # Prepare the sample data file
26-
... with open(tmpfile.name, mode="w") as fp:
27+
... with Path(tmpfile.name).open(mode="w") as fp:
2728
... print(">", file=fp)
2829
... print("1.0 2.0 3.0 TEXT1 TEXT23", file=fp)
2930
... print("4.0 5.0 6.0 TEXT4 TEXT567", file=fp)
@@ -157,12 +158,13 @@ def to_dataframe(self) -> pd.DataFrame:
157158
158159
Examples
159160
--------
161+
>>> from pathlib import Path
160162
>>> from pygmt.helpers import GMTTempFile
161163
>>> from pygmt.clib import Session
162164
>>>
163165
>>> with GMTTempFile(suffix=".txt") as tmpfile:
164166
... # prepare the sample data file
165-
... with open(tmpfile.name, mode="w") as fp:
167+
... with Path(tmpfile.name).open(mode="w") as fp:
166168
... print(">", file=fp)
167169
... print("1.0 2.0 3.0 TEXT1 TEXT23", file=fp)
168170
... print("4.0 5.0 6.0 TEXT4 TEXT567", file=fp)

pygmt/figure.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -497,9 +497,7 @@ def _preview(self, fmt, dpi, as_bytes=False, **kwargs):
497497
fname = Path(self._preview_dir.name) / f"{self._name}.{fmt}"
498498
self.savefig(fname, dpi=dpi, **kwargs)
499499
if as_bytes:
500-
with open(fname, "rb") as image:
501-
preview = image.read()
502-
return preview
500+
return fname.read_bytes()
503501
return fname
504502

505503
def _repr_png_(self):

pygmt/helpers/tempfile.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -88,11 +88,10 @@ def read(self, keep_tabs=False):
8888
content : str
8989
Content of the temporary file as a Unicode string.
9090
"""
91-
with open(self.name, encoding="utf8") as tmpfile:
92-
content = tmpfile.read()
93-
if not keep_tabs:
94-
content = content.replace("\t", " ")
95-
return content
91+
content = Path(self.name).read_text(encoding="utf8")
92+
if not keep_tabs:
93+
content = content.replace("\t", " ")
94+
return content
9695

9796
def loadtxt(self, **kwargs):
9897
"""

pygmt/src/plot.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
plot - Plot in two dimensions.
33
"""
44

5+
from pathlib import Path
6+
57
from pygmt.clib import Session
68
from pygmt.exceptions import GMTInvalidInput
79
from pygmt.helpers import (
@@ -220,7 +222,7 @@ def plot( # noqa: PLR0912
220222
elif kwargs.get("S") is None and kind == "file" and str(data).endswith(".gmt"):
221223
# checking that the data is a file path to set default style
222224
try:
223-
with open(which(data), encoding="utf8") as file:
225+
with Path(which(data)).open(encoding="utf8") as file:
224226
line = file.readline()
225227
if "@GMULTIPOINT" in line or "@GPOINT" in line:
226228
# if the file is gmt style and geometry is set to Point

pygmt/src/plot3d.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
plot3d - Plot in three dimensions.
33
"""
44

5+
from pathlib import Path
6+
57
from pygmt.clib import Session
68
from pygmt.exceptions import GMTInvalidInput
79
from pygmt.helpers import (
@@ -195,7 +197,7 @@ def plot3d( # noqa: PLR0912
195197
elif kwargs.get("S") is None and kind == "file" and str(data).endswith(".gmt"):
196198
# checking that the data is a file path to set default style
197199
try:
198-
with open(which(data), encoding="utf8") as file:
200+
with Path(which(data)).open(encoding="utf8") as file:
199201
line = file.readline()
200202
if "@GMULTIPOINT" in line or "@GPOINT" in line:
201203
# if the file is gmt style and geometry is set to Point

pygmt/tests/test_helpers.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,7 @@ def test_gmttempfile_read():
132132
Make sure GMTTempFile.read() works.
133133
"""
134134
with GMTTempFile() as tmpfile:
135-
with open(tmpfile.name, "w", encoding="utf8") as ftmp:
136-
ftmp.write("in.dat: N = 2\t<1/3>\t<2/4>\n")
135+
Path(tmpfile.name).write_text("in.dat: N = 2\t<1/3>\t<2/4>\n")
137136
assert tmpfile.read() == "in.dat: N = 2 <1/3> <2/4>\n"
138137
assert tmpfile.read(keep_tabs=True) == "in.dat: N = 2\t<1/3>\t<2/4>\n"
139138

pygmt/tests/test_legend.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
Test Figure.legend.
33
"""
44

5+
from pathlib import Path
6+
57
import pytest
68
from pygmt import Figure
79
from pygmt.exceptions import GMTInvalidInput
@@ -95,8 +97,7 @@ def test_legend_specfile():
9597
"""
9698

9799
with GMTTempFile() as specfile:
98-
with open(specfile.name, "w", encoding="utf8") as file:
99-
file.write(specfile_contents)
100+
Path(specfile.name).write_text(specfile_contents)
100101
fig = Figure()
101102
fig.basemap(projection="x6i", region=[0, 1, 0, 1], frame=True)
102103
fig.legend(specfile.name, position="JTM+jCM+w5i")

pygmt/tests/test_meca.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
Test Figure.meca.
33
"""
44

5+
from pathlib import Path
6+
57
import numpy as np
68
import pandas as pd
79
import pytest
@@ -72,13 +74,8 @@ def test_meca_spec_single_focalmecha_file():
7274
fig = Figure()
7375
fig.basemap(region=[-1, 1, 4, 6], projection="M8c", frame=2)
7476
with GMTTempFile() as temp:
75-
with open(temp.name, mode="w", encoding="utf8") as temp_file:
76-
temp_file.write("0 5 0 0 90 0 5")
77-
fig.meca(
78-
spec=temp.name,
79-
convention="aki",
80-
scale="2.5c",
81-
)
77+
Path(temp.name).write_text("0 5 0 0 90 0 5")
78+
fig.meca(spec=temp.name, convention="aki", scale="2.5c")
8279
return fig
8380

8481

pygmt/tests/test_plot.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -487,8 +487,7 @@ def test_plot_ogrgmt_file_multipoint_default_style(func):
487487
# FEATURE_DATA
488488
1 2
489489
"""
490-
with open(tmpfile.name, "w", encoding="utf8") as file:
491-
file.write(gmt_file)
490+
Path(tmpfile.name).write_text(gmt_file)
492491
fig = Figure()
493492
fig.plot(
494493
data=func(tmpfile.name), region=[0, 2, 1, 3], projection="X2c", frame=True
@@ -507,8 +506,7 @@ def test_plot_ogrgmt_file_multipoint_non_default_style():
507506
# FEATURE_DATA
508507
1 2
509508
"""
510-
with open(tmpfile.name, "w", encoding="utf8") as file:
511-
file.write(gmt_file)
509+
Path(tmpfile.name).write_text(gmt_file)
512510
fig = Figure()
513511
fig.plot(
514512
data=tmpfile.name,

pygmt/tests/test_plot3d.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -444,8 +444,7 @@ def test_plot3d_ogrgmt_file_multipoint_default_style(func):
444444
>
445445
1 1 2
446446
1.5 1.5 1"""
447-
with open(tmpfile.name, "w", encoding="utf8") as file:
448-
file.write(gmt_file)
447+
Path(tmpfile.name).write_text(gmt_file)
449448
fig = Figure()
450449
fig.plot3d(
451450
data=func(tmpfile.name),
@@ -470,8 +469,7 @@ def test_plot3d_ogrgmt_file_multipoint_non_default_style():
470469
>
471470
1 1 2
472471
1.5 1.5 1"""
473-
with open(tmpfile.name, "w", encoding="utf8") as file:
474-
file.write(gmt_file)
472+
Path(tmpfile.name).write_text(gmt_file)
475473
fig = Figure()
476474
fig.plot3d(
477475
data=tmpfile.name,

pygmt/tests/test_text.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -299,8 +299,7 @@ def test_text_angle_font_justify_from_textfile():
299299
"""
300300
fig = Figure()
301301
with GMTTempFile(suffix=".txt") as tempfile:
302-
with open(tempfile.name, "w", encoding="utf8") as tmpfile:
303-
tmpfile.write("114 0.5 30 22p,Helvetica-Bold,black LM BORNEO")
302+
Path(tempfile.name).write_text("114 0.5 30 22p,Helvetica-Bold,black LM BORNEO")
304303
fig.text(
305304
region=[113, 117.5, -0.5, 3],
306305
projection="M5c",

pygmt/tests/test_x2sys_cross.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def _fixture_mock_x2sys_home(monkeypatch):
2424
Set the X2SYS_HOME environment variable to the current working directory for the
2525
test session.
2626
"""
27-
monkeypatch.setenv("X2SYS_HOME", Path.cwd())
27+
monkeypatch.setenv("X2SYS_HOME", str(Path.cwd()))
2828

2929

3030
@pytest.fixture(scope="module", name="tracks")
@@ -115,7 +115,7 @@ def test_x2sys_cross_input_two_dataframes():
115115
)
116116

117117
# Add a time row to the x2sys fmtfile
118-
with open(tmpdir_p / "xyz.fmt", mode="a", encoding="utf8") as fmtfile:
118+
with (tmpdir_p / "xyz.fmt").open(mode="a", encoding="utf8") as fmtfile:
119119
fmtfile.write("time\ta\tN\t0\t1\t0\t%g\n")
120120

121121
# Create pandas.DataFrame track tables
@@ -175,10 +175,7 @@ def test_x2sys_cross_input_two_filenames():
175175
# Create temporary xyz files
176176
for i in range(2):
177177
rng = np.random.default_rng(seed=i)
178-
with open(
179-
Path.cwd() / f"track_{i}.xyz", mode="w", encoding="utf8"
180-
) as fname:
181-
np.savetxt(fname=fname, X=rng.random((10, 3)))
178+
np.savetxt(fname=Path.cwd() / f"track_{i}.xyz", X=rng.random((10, 3)))
182179

183180
output = x2sys_cross(tracks=["track_0.xyz", "track_1.xyz"], tag=tag, coe="e")
184181

pygmt/tests/test_x2sys_init.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def _fixture_mock_x2sys_home(monkeypatch):
1515
Set the X2SYS_HOME environment variable to the current working directory for the
1616
test session.
1717
"""
18-
monkeypatch.setenv("X2SYS_HOME", Path.cwd())
18+
monkeypatch.setenv("X2SYS_HOME", str(Path.cwd()))
1919

2020

2121
@pytest.mark.usefixtures("mock_x2sys_home")
@@ -30,11 +30,9 @@ def test_x2sys_init_region_spacing():
3030
x2sys_init(
3131
tag=tag, fmtfile="xyz", force=True, region=[0, 10, 20, 30], spacing=[5, 5]
3232
)
33-
34-
with open(tmpdir_p / f"{tag}.tag", encoding="utf8") as tagpath:
35-
tail_line = tagpath.readlines()[-1]
36-
assert "-R0/10/20/30" in tail_line
37-
assert "-I5/5" in tail_line
33+
tail_line = (tmpdir_p / f"{tag}.tag").read_text().splitlines()[-1]
34+
assert "-R0/10/20/30" in tail_line
35+
assert "-I5/5" in tail_line
3836

3937

4038
@pytest.mark.benchmark
@@ -54,7 +52,6 @@ def test_x2sys_init_units_gap():
5452
gap=["tseconds", "de"],
5553
)
5654

57-
with open(tmpdir_p / f"{tag}.tag", encoding="utf8") as tagpath:
58-
tail_line = tagpath.readlines()[-1]
59-
assert "-Nse -Nde" in tail_line
60-
assert "-Wtseconds -Wde" in tail_line
55+
tail_line = (tmpdir_p / f"{tag}.tag").read_text().splitlines()[-1]
56+
assert "-Nse -Nde" in tail_line
57+
assert "-Wtseconds -Wde" in tail_line

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ select = [
107107
"PIE", # flake8-pie
108108
"PL", # pylint
109109
"PT", # flake8-pytest-style
110+
"PTH", # flake8-use-pathlib
110111
"RET", # flake8-return
111112
"RSE", # flake8-raise
112113
"RUF", # ruff-specific

0 commit comments

Comments
 (0)