Skip to content

Commit

Permalink
Enable ruff's PTH (flake8-use-pathlib) rules and fix violations (#3129)
Browse files Browse the repository at this point in the history
  • Loading branch information
seisman authored Mar 20, 2024
1 parent 0cdb87d commit dd8e0cd
Show file tree
Hide file tree
Showing 16 changed files with 46 additions and 55 deletions.
2 changes: 1 addition & 1 deletion examples/tutorials/basics/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
fig.coast(land="black", water="skyblue")

# Create space-delimited file
with open("examples.txt", "w") as f:
with Path("examples.txt").open(mode="w") as f:
f.write("114 0.5 0 22p,Helvetica-Bold,white CM BORNEO\n")
f.write("119 3.25 0 12p,Helvetica-Bold,black CM CELEBES SEA\n")
f.write("112 -4.6 0 12p,Helvetica-Bold,black CM JAVA SEA\n")
Expand Down
11 changes: 6 additions & 5 deletions pygmt/clib/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -1641,12 +1641,13 @@ def virtualfile_out(
Examples
--------
>>> from pathlib import Path
>>> from pygmt.clib import Session
>>> from pygmt.datatypes import _GMT_DATASET
>>> from pygmt.helpers import GMTTempFile
>>>
>>> with GMTTempFile(suffix=".txt") as tmpfile:
... with open(tmpfile.name, mode="w") as fp:
... with Path(tmpfile.name).open(mode="w") as fp:
... print("1.0 2.0 3.0 TEXT", file=fp)
...
... # Create a virtual file for storing the output table.
Expand All @@ -1661,8 +1662,7 @@ def virtualfile_out(
... with lib.virtualfile_out(fname=tmpfile.name) as vouttbl:
... assert vouttbl == tmpfile.name
... lib.call_module("read", f"{tmpfile.name} {vouttbl} -Td")
... with open(vouttbl, mode="r") as fp:
... line = fp.readline()
... line = Path(vouttbl).read_text()
... assert line == "1\t2\t3\tTEXT\n"
"""
if fname is not None: # Yield the actual file name.
Expand Down Expand Up @@ -1692,13 +1692,14 @@ def read_virtualfile(
Examples
--------
>>> from pathlib import Path
>>> from pygmt.clib import Session
>>> from pygmt.helpers import GMTTempFile
>>>
>>> # Read dataset from a virtual file
>>> with Session() as lib:
... with GMTTempFile(suffix=".txt") as tmpfile:
... with open(tmpfile.name, mode="w") as fp:
... with Path(tmpfile.name).open(mode="w") as fp:
... print("1.0 2.0 3.0 TEXT", file=fp)
... with lib.virtualfile_out(kind="dataset") as vouttbl:
... lib.call_module("read", f"{tmpfile.name} {vouttbl} -Td")
Expand Down Expand Up @@ -1779,7 +1780,7 @@ def virtualfile_to_dataset(
>>>
>>> with GMTTempFile(suffix=".txt") as tmpfile:
... # prepare the sample data file
... with open(tmpfile.name, mode="w") as fp:
... with Path(tmpfile.name).open(mode="w") as fp:
... print(">", file=fp)
... print("1.0 2.0 3.0 TEXT1 TEXT23", file=fp)
... print("4.0 5.0 6.0 TEXT4 TEXT567", file=fp)
Expand Down
6 changes: 4 additions & 2 deletions pygmt/datatypes/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@ class _GMT_DATASET(ctp.Structure): # noqa: N801
Examples
--------
>>> from pathlib import Path
>>> from pygmt.helpers import GMTTempFile
>>> from pygmt.clib import Session
>>>
>>> with GMTTempFile(suffix=".txt") as tmpfile:
... # Prepare the sample data file
... with open(tmpfile.name, mode="w") as fp:
... with Path(tmpfile.name).open(mode="w") as fp:
... print(">", file=fp)
... print("1.0 2.0 3.0 TEXT1 TEXT23", file=fp)
... print("4.0 5.0 6.0 TEXT4 TEXT567", file=fp)
Expand Down Expand Up @@ -157,12 +158,13 @@ def to_dataframe(self) -> pd.DataFrame:
Examples
--------
>>> from pathlib import Path
>>> from pygmt.helpers import GMTTempFile
>>> from pygmt.clib import Session
>>>
>>> with GMTTempFile(suffix=".txt") as tmpfile:
... # prepare the sample data file
... with open(tmpfile.name, mode="w") as fp:
... with Path(tmpfile.name).open(mode="w") as fp:
... print(">", file=fp)
... print("1.0 2.0 3.0 TEXT1 TEXT23", file=fp)
... print("4.0 5.0 6.0 TEXT4 TEXT567", file=fp)
Expand Down
4 changes: 1 addition & 3 deletions pygmt/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,9 +497,7 @@ def _preview(self, fmt, dpi, as_bytes=False, **kwargs):
fname = Path(self._preview_dir.name) / f"{self._name}.{fmt}"
self.savefig(fname, dpi=dpi, **kwargs)
if as_bytes:
with open(fname, "rb") as image:
preview = image.read()
return preview
return fname.read_bytes()
return fname

def _repr_png_(self):
Expand Down
9 changes: 4 additions & 5 deletions pygmt/helpers/tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,10 @@ def read(self, keep_tabs=False):
content : str
Content of the temporary file as a Unicode string.
"""
with open(self.name, encoding="utf8") as tmpfile:
content = tmpfile.read()
if not keep_tabs:
content = content.replace("\t", " ")
return content
content = Path(self.name).read_text(encoding="utf8")
if not keep_tabs:
content = content.replace("\t", " ")
return content

def loadtxt(self, **kwargs):
"""
Expand Down
4 changes: 3 additions & 1 deletion pygmt/src/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
plot - Plot in two dimensions.
"""

from pathlib import Path

from pygmt.clib import Session
from pygmt.exceptions import GMTInvalidInput
from pygmt.helpers import (
Expand Down Expand Up @@ -220,7 +222,7 @@ def plot( # noqa: PLR0912
elif kwargs.get("S") is None and kind == "file" and str(data).endswith(".gmt"):
# checking that the data is a file path to set default style
try:
with open(which(data), encoding="utf8") as file:
with Path(which(data)).open(encoding="utf8") as file:
line = file.readline()
if "@GMULTIPOINT" in line or "@GPOINT" in line:
# if the file is gmt style and geometry is set to Point
Expand Down
4 changes: 3 additions & 1 deletion pygmt/src/plot3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
plot3d - Plot in three dimensions.
"""

from pathlib import Path

from pygmt.clib import Session
from pygmt.exceptions import GMTInvalidInput
from pygmt.helpers import (
Expand Down Expand Up @@ -195,7 +197,7 @@ def plot3d( # noqa: PLR0912
elif kwargs.get("S") is None and kind == "file" and str(data).endswith(".gmt"):
# checking that the data is a file path to set default style
try:
with open(which(data), encoding="utf8") as file:
with Path(which(data)).open(encoding="utf8") as file:
line = file.readline()
if "@GMULTIPOINT" in line or "@GPOINT" in line:
# if the file is gmt style and geometry is set to Point
Expand Down
3 changes: 1 addition & 2 deletions pygmt/tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,7 @@ def test_gmttempfile_read():
Make sure GMTTempFile.read() works.
"""
with GMTTempFile() as tmpfile:
with open(tmpfile.name, "w", encoding="utf8") as ftmp:
ftmp.write("in.dat: N = 2\t<1/3>\t<2/4>\n")
Path(tmpfile.name).write_text("in.dat: N = 2\t<1/3>\t<2/4>\n")
assert tmpfile.read() == "in.dat: N = 2 <1/3> <2/4>\n"
assert tmpfile.read(keep_tabs=True) == "in.dat: N = 2\t<1/3>\t<2/4>\n"

Expand Down
5 changes: 3 additions & 2 deletions pygmt/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
Test Figure.legend.
"""

from pathlib import Path

import pytest
from pygmt import Figure
from pygmt.exceptions import GMTInvalidInput
Expand Down Expand Up @@ -95,8 +97,7 @@ def test_legend_specfile():
"""

with GMTTempFile() as specfile:
with open(specfile.name, "w", encoding="utf8") as file:
file.write(specfile_contents)
Path(specfile.name).write_text(specfile_contents)
fig = Figure()
fig.basemap(projection="x6i", region=[0, 1, 0, 1], frame=True)
fig.legend(specfile.name, position="JTM+jCM+w5i")
Expand Down
11 changes: 4 additions & 7 deletions pygmt/tests/test_meca.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
Test Figure.meca.
"""

from pathlib import Path

import numpy as np
import pandas as pd
import pytest
Expand Down Expand Up @@ -72,13 +74,8 @@ def test_meca_spec_single_focalmecha_file():
fig = Figure()
fig.basemap(region=[-1, 1, 4, 6], projection="M8c", frame=2)
with GMTTempFile() as temp:
with open(temp.name, mode="w", encoding="utf8") as temp_file:
temp_file.write("0 5 0 0 90 0 5")
fig.meca(
spec=temp.name,
convention="aki",
scale="2.5c",
)
Path(temp.name).write_text("0 5 0 0 90 0 5")
fig.meca(spec=temp.name, convention="aki", scale="2.5c")
return fig


Expand Down
6 changes: 2 additions & 4 deletions pygmt/tests/test_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,8 +487,7 @@ def test_plot_ogrgmt_file_multipoint_default_style(func):
# FEATURE_DATA
1 2
"""
with open(tmpfile.name, "w", encoding="utf8") as file:
file.write(gmt_file)
Path(tmpfile.name).write_text(gmt_file)
fig = Figure()
fig.plot(
data=func(tmpfile.name), region=[0, 2, 1, 3], projection="X2c", frame=True
Expand All @@ -507,8 +506,7 @@ def test_plot_ogrgmt_file_multipoint_non_default_style():
# FEATURE_DATA
1 2
"""
with open(tmpfile.name, "w", encoding="utf8") as file:
file.write(gmt_file)
Path(tmpfile.name).write_text(gmt_file)
fig = Figure()
fig.plot(
data=tmpfile.name,
Expand Down
6 changes: 2 additions & 4 deletions pygmt/tests/test_plot3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -444,8 +444,7 @@ def test_plot3d_ogrgmt_file_multipoint_default_style(func):
>
1 1 2
1.5 1.5 1"""
with open(tmpfile.name, "w", encoding="utf8") as file:
file.write(gmt_file)
Path(tmpfile.name).write_text(gmt_file)
fig = Figure()
fig.plot3d(
data=func(tmpfile.name),
Expand All @@ -470,8 +469,7 @@ def test_plot3d_ogrgmt_file_multipoint_non_default_style():
>
1 1 2
1.5 1.5 1"""
with open(tmpfile.name, "w", encoding="utf8") as file:
file.write(gmt_file)
Path(tmpfile.name).write_text(gmt_file)
fig = Figure()
fig.plot3d(
data=tmpfile.name,
Expand Down
3 changes: 1 addition & 2 deletions pygmt/tests/test_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,8 +299,7 @@ def test_text_angle_font_justify_from_textfile():
"""
fig = Figure()
with GMTTempFile(suffix=".txt") as tempfile:
with open(tempfile.name, "w", encoding="utf8") as tmpfile:
tmpfile.write("114 0.5 30 22p,Helvetica-Bold,black LM BORNEO")
Path(tempfile.name).write_text("114 0.5 30 22p,Helvetica-Bold,black LM BORNEO")
fig.text(
region=[113, 117.5, -0.5, 3],
projection="M5c",
Expand Down
9 changes: 3 additions & 6 deletions pygmt/tests/test_x2sys_cross.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def _fixture_mock_x2sys_home(monkeypatch):
Set the X2SYS_HOME environment variable to the current working directory for the
test session.
"""
monkeypatch.setenv("X2SYS_HOME", Path.cwd())
monkeypatch.setenv("X2SYS_HOME", str(Path.cwd()))


@pytest.fixture(scope="module", name="tracks")
Expand Down Expand Up @@ -115,7 +115,7 @@ def test_x2sys_cross_input_two_dataframes():
)

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

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

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

Expand Down
17 changes: 7 additions & 10 deletions pygmt/tests/test_x2sys_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def _fixture_mock_x2sys_home(monkeypatch):
Set the X2SYS_HOME environment variable to the current working directory for the
test session.
"""
monkeypatch.setenv("X2SYS_HOME", Path.cwd())
monkeypatch.setenv("X2SYS_HOME", str(Path.cwd()))


@pytest.mark.usefixtures("mock_x2sys_home")
Expand All @@ -30,11 +30,9 @@ def test_x2sys_init_region_spacing():
x2sys_init(
tag=tag, fmtfile="xyz", force=True, region=[0, 10, 20, 30], spacing=[5, 5]
)

with open(tmpdir_p / f"{tag}.tag", encoding="utf8") as tagpath:
tail_line = tagpath.readlines()[-1]
assert "-R0/10/20/30" in tail_line
assert "-I5/5" in tail_line
tail_line = (tmpdir_p / f"{tag}.tag").read_text().splitlines()[-1]
assert "-R0/10/20/30" in tail_line
assert "-I5/5" in tail_line


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

with open(tmpdir_p / f"{tag}.tag", encoding="utf8") as tagpath:
tail_line = tagpath.readlines()[-1]
assert "-Nse -Nde" in tail_line
assert "-Wtseconds -Wde" in tail_line
tail_line = (tmpdir_p / f"{tag}.tag").read_text().splitlines()[-1]
assert "-Nse -Nde" in tail_line
assert "-Wtseconds -Wde" in tail_line
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ select = [
"PIE", # flake8-pie
"PL", # pylint
"PT", # flake8-pytest-style
"PTH", # flake8-use-pathlib
"RET", # flake8-return
"RSE", # flake8-raise
"RUF", # ruff-specific
Expand Down

0 comments on commit dd8e0cd

Please sign in to comment.