Skip to content

Commit da38c66

Browse files
committed
SIM105: Replace try-except-pass blocks with the contextlib.suppress context manager
1 parent 2454aa6 commit da38c66

File tree

5 files changed

+16
-21
lines changed

5 files changed

+16
-21
lines changed

pygmt/clib/loading.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
environment variable :term:`GMT_LIBRARY_PATH`.
66
"""
77

8+
import contextlib
89
import ctypes
910
import os
1011
import shutil
@@ -160,14 +161,13 @@ def clib_full_names(env: Mapping | None = None) -> Iterator[str]:
160161
# 2. Search for the library returned by command "gmt --show-library".
161162
# Use `str(Path(realpath))` to avoid mixture of separators "\\" and "/".
162163
if gmtbin := shutil.which("gmt"):
163-
try:
164+
# Suppress the CalledProcessError when the 'gmt' executable is broken
165+
with contextlib.suppress(sp.CalledProcessError):
164166
libfullpath = Path(
165167
sp.check_output([gmtbin, "--show-library"], encoding="utf-8").rstrip()
166168
)
167169
if libfullpath.exists():
168170
yield str(libfullpath)
169-
except sp.CalledProcessError: # the 'gmt' executable is broken
170-
pass
171171

172172
# 3. Search for DLLs in PATH by calling find_library() (Windows only)
173173
if sys.platform == "win32":

pygmt/clib/session.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -353,19 +353,17 @@ def create(self, name):
353353
name : str
354354
A name for this session. Doesn't really affect the outcome.
355355
"""
356-
try:
357-
# Won't raise an exception if there is a currently open session
356+
# Check if there is a currently open session by accessing the session pointer.
357+
# If not, the GMTCLibNoSessionError exception will be raised and we will ignore
358+
# it and continue to create a new session. Otherwise, it means there is an open
359+
# session and we will raise a GMTCLibError exception.
360+
with contextlib.suppress(GMTCLibNoSessionError):
358361
_ = self.session_pointer
359-
# In this case, fail to create a new session until the old one is
360-
# destroyed
361-
raise GMTCLibError(
362+
msg = (
362363
"Failed to create a GMT API session: There is a currently open session."
363364
" Must destroy it first."
364365
)
365-
# If the exception is raised, this means that there is no open session
366-
# and we're free to create a new one.
367-
except GMTCLibNoSessionError:
368-
pass
366+
raise GMTCLibError(msg)
369367

370368
c_create_session = self.get_libgmt_func(
371369
"GMT_Create_Session",

pygmt/src/plot.py

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

5+
import contextlib
56
from pathlib import Path
67

78
from pygmt.clib import Session
@@ -246,13 +247,11 @@ def plot( # noqa: PLR0912
246247
if kind == "geojson" and data.geom_type.isin(["Point", "MultiPoint"]).all():
247248
kwargs["S"] = "s0.2c"
248249
elif kind == "file" and str(data).endswith(".gmt"): # OGR_GMT file
249-
try:
250+
with contextlib.suppress(FileNotFoundError):
250251
with Path(which(data)).open(encoding="utf-8") as file:
251252
line = file.readline()
252253
if "@GMULTIPOINT" in line or "@GPOINT" in line:
253254
kwargs["S"] = "s0.2c"
254-
except FileNotFoundError:
255-
pass
256255

257256
with Session() as lib:
258257
with lib.virtualfile_in(

pygmt/src/plot3d.py

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

5+
import contextlib
56
from pathlib import Path
67

78
from pygmt.clib import Session
@@ -222,13 +223,11 @@ def plot3d( # noqa: PLR0912
222223
if kind == "geojson" and data.geom_type.isin(["Point", "MultiPoint"]).all():
223224
kwargs["S"] = "u0.2c"
224225
elif kind == "file" and str(data).endswith(".gmt"): # OGR_GMT file
225-
try:
226+
with contextlib.suppress(FileNotFoundError):
226227
with Path(which(data)).open(encoding="utf-8") as file:
227228
line = file.readline()
228229
if "@GMULTIPOINT" in line or "@GPOINT" in line:
229230
kwargs["S"] = "u0.2c"
230-
except FileNotFoundError:
231-
pass
232231

233232
with Session() as lib:
234233
with lib.virtualfile_in(

pygmt/tests/test_figure.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
Doesn't include the plotting commands which have their own test files.
55
"""
66

7+
import contextlib
78
from pathlib import Path
89

910
import numpy as np
@@ -112,7 +113,7 @@ def test_figure_savefig_geotiff():
112113
assert fname.exists()
113114

114115
# Check if a TIFF is georeferenced or not
115-
try:
116+
with contextlib.suppress(ImportError): # Skip if failed to import
116117
import rioxarray
117118
from rasterio.errors import NotGeoreferencedWarning
118119
from rasterio.transform import Affine
@@ -150,8 +151,6 @@ def test_figure_savefig_geotiff():
150151
a=1.0, b=0.0, c=0.0, d=0.0, e=1.0, f=0.0
151152
)
152153
assert len(record) == 1
153-
except ImportError:
154-
pass
155154
geofname.unlink()
156155
fname.unlink()
157156

0 commit comments

Comments
 (0)