From da38c668b73b2c425ce1af80aea20f84625843df Mon Sep 17 00:00:00 2001 From: Dongdong Tian Date: Mon, 23 Sep 2024 21:30:14 +0800 Subject: [PATCH 1/2] SIM105: Replace try-except-pass blocks with the contextlib.suppress context manager --- pygmt/clib/loading.py | 6 +++--- pygmt/clib/session.py | 16 +++++++--------- pygmt/src/plot.py | 5 ++--- pygmt/src/plot3d.py | 5 ++--- pygmt/tests/test_figure.py | 5 ++--- 5 files changed, 16 insertions(+), 21 deletions(-) diff --git a/pygmt/clib/loading.py b/pygmt/clib/loading.py index 7034bf103df..e82ea26d093 100644 --- a/pygmt/clib/loading.py +++ b/pygmt/clib/loading.py @@ -5,6 +5,7 @@ environment variable :term:`GMT_LIBRARY_PATH`. """ +import contextlib import ctypes import os import shutil @@ -160,14 +161,13 @@ def clib_full_names(env: Mapping | None = None) -> Iterator[str]: # 2. Search for the library returned by command "gmt --show-library". # Use `str(Path(realpath))` to avoid mixture of separators "\\" and "/". if gmtbin := shutil.which("gmt"): - try: + # Suppress the CalledProcessError when the 'gmt' executable is broken + with contextlib.suppress(sp.CalledProcessError): libfullpath = Path( sp.check_output([gmtbin, "--show-library"], encoding="utf-8").rstrip() ) if libfullpath.exists(): yield str(libfullpath) - except sp.CalledProcessError: # the 'gmt' executable is broken - pass # 3. Search for DLLs in PATH by calling find_library() (Windows only) if sys.platform == "win32": diff --git a/pygmt/clib/session.py b/pygmt/clib/session.py index 95ed8c19d76..8418e855add 100644 --- a/pygmt/clib/session.py +++ b/pygmt/clib/session.py @@ -353,19 +353,17 @@ def create(self, name): name : str A name for this session. Doesn't really affect the outcome. """ - try: - # Won't raise an exception if there is a currently open session + # Check if there is a currently open session by accessing the session pointer. + # If not, the GMTCLibNoSessionError exception will be raised and we will ignore + # it and continue to create a new session. Otherwise, it means there is an open + # session and we will raise a GMTCLibError exception. + with contextlib.suppress(GMTCLibNoSessionError): _ = self.session_pointer - # In this case, fail to create a new session until the old one is - # destroyed - raise GMTCLibError( + msg = ( "Failed to create a GMT API session: There is a currently open session." " Must destroy it first." ) - # If the exception is raised, this means that there is no open session - # and we're free to create a new one. - except GMTCLibNoSessionError: - pass + raise GMTCLibError(msg) c_create_session = self.get_libgmt_func( "GMT_Create_Session", diff --git a/pygmt/src/plot.py b/pygmt/src/plot.py index e66f08438e5..b80ec1e232e 100644 --- a/pygmt/src/plot.py +++ b/pygmt/src/plot.py @@ -2,6 +2,7 @@ plot - Plot in two dimensions. """ +import contextlib from pathlib import Path from pygmt.clib import Session @@ -246,13 +247,11 @@ def plot( # noqa: PLR0912 if kind == "geojson" and data.geom_type.isin(["Point", "MultiPoint"]).all(): kwargs["S"] = "s0.2c" elif kind == "file" and str(data).endswith(".gmt"): # OGR_GMT file - try: + with contextlib.suppress(FileNotFoundError): with Path(which(data)).open(encoding="utf-8") as file: line = file.readline() if "@GMULTIPOINT" in line or "@GPOINT" in line: kwargs["S"] = "s0.2c" - except FileNotFoundError: - pass with Session() as lib: with lib.virtualfile_in( diff --git a/pygmt/src/plot3d.py b/pygmt/src/plot3d.py index c86e5e259f1..ed7be05169d 100644 --- a/pygmt/src/plot3d.py +++ b/pygmt/src/plot3d.py @@ -2,6 +2,7 @@ plot3d - Plot in three dimensions. """ +import contextlib from pathlib import Path from pygmt.clib import Session @@ -222,13 +223,11 @@ def plot3d( # noqa: PLR0912 if kind == "geojson" and data.geom_type.isin(["Point", "MultiPoint"]).all(): kwargs["S"] = "u0.2c" elif kind == "file" and str(data).endswith(".gmt"): # OGR_GMT file - try: + with contextlib.suppress(FileNotFoundError): with Path(which(data)).open(encoding="utf-8") as file: line = file.readline() if "@GMULTIPOINT" in line or "@GPOINT" in line: kwargs["S"] = "u0.2c" - except FileNotFoundError: - pass with Session() as lib: with lib.virtualfile_in( diff --git a/pygmt/tests/test_figure.py b/pygmt/tests/test_figure.py index 4c8e184d118..efaa51ef671 100644 --- a/pygmt/tests/test_figure.py +++ b/pygmt/tests/test_figure.py @@ -4,6 +4,7 @@ Doesn't include the plotting commands which have their own test files. """ +import contextlib from pathlib import Path import numpy as np @@ -112,7 +113,7 @@ def test_figure_savefig_geotiff(): assert fname.exists() # Check if a TIFF is georeferenced or not - try: + with contextlib.suppress(ImportError): # Skip if failed to import import rioxarray from rasterio.errors import NotGeoreferencedWarning from rasterio.transform import Affine @@ -150,8 +151,6 @@ def test_figure_savefig_geotiff(): a=1.0, b=0.0, c=0.0, d=0.0, e=1.0, f=0.0 ) assert len(record) == 1 - except ImportError: - pass geofname.unlink() fname.unlink() From a6c47daa397840a278138b01fc7ea64cc6d37432 Mon Sep 17 00:00:00 2001 From: Dongdong Tian Date: Tue, 24 Sep 2024 08:03:25 +0800 Subject: [PATCH 2/2] Also update a few type hints in clib/loading.py --- pygmt/clib/loading.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pygmt/clib/loading.py b/pygmt/clib/loading.py index e82ea26d093..34640a11705 100644 --- a/pygmt/clib/loading.py +++ b/pygmt/clib/loading.py @@ -123,7 +123,7 @@ def clib_names(os_name: str) -> list[str]: return libnames -def clib_full_names(env: Mapping | None = None) -> Iterator[str]: +def clib_full_names(env: Mapping[str, str] | None = None) -> Iterator[str]: """ Return full path(s) of GMT shared library for the current operating system. @@ -180,7 +180,7 @@ def clib_full_names(env: Mapping | None = None) -> Iterator[str]: yield libname -def check_libgmt(libgmt: ctypes.CDLL): +def check_libgmt(libgmt: ctypes.CDLL) -> None: """ Make sure the GMT shared library was loaded correctly. @@ -198,7 +198,7 @@ def check_libgmt(libgmt: ctypes.CDLL): GMTCLibError """ for func in ["Create_Session", "Get_Enum", "Call_Module", "Destroy_Session"]: - if not hasattr(libgmt, "GMT_" + func): + if not hasattr(libgmt, f"GMT_{func}"): msg = ( f"Error loading '{libgmt._name}'. Couldn't access function GMT_{func}. " "Ensure that you have installed an up-to-date GMT version 6 library and "