diff --git a/pygmt/clib/conversion.py b/pygmt/clib/conversion.py index 44142446214..47b3aacfbd6 100644 --- a/pygmt/clib/conversion.py +++ b/pygmt/clib/conversion.py @@ -109,16 +109,16 @@ def dataarray_to_matrix( # Calculate the increment if irregular spacing is found. coord_inc = (coord[-1] - coord[0]) / (coord.size - 1) msg = ( - f"Grid may have irregular spacing in the '{dim}' dimension, " + f"Grid may have irregular spacing in the {dim!r} dimension, " "but GMT only supports regular spacing. Calculated regular spacing " - f"{coord_inc} is assumed in the '{dim}' dimension." + f"{coord_inc} is assumed in the {dim!r} dimension." ) warnings.warn(msg, category=RuntimeWarning, stacklevel=2) if coord_inc == 0: raise GMTValueError( coord_inc, description="grid increment", - reason=f"Grid has a zero increment in the '{dim}' dimension.", + reason=f"Grid has a zero increment in the {dim!r} dimension.", ) region.extend( [ diff --git a/pygmt/clib/loading.py b/pygmt/clib/loading.py index c6bc446c8e0..8b1ffd3357d 100644 --- a/pygmt/clib/loading.py +++ b/pygmt/clib/loading.py @@ -55,7 +55,7 @@ def load_libgmt(lib_fullnames: Iterator[str] | None = None) -> ctypes.CDLL: error = False break except (OSError, GMTCLibError) as err: - error_msg.append(f"Error loading GMT shared library at '{libname}'.\n{err}") + error_msg.append(f"Error loading GMT shared library at {libname!r}.\n{err}") failing_libs.append(libname) if error: @@ -118,7 +118,7 @@ def clib_names(os_name: str) -> list[str]: case "win32": # Windows libnames = ["gmt.dll", "gmt_w64.dll", "gmt_w32.dll"] case _: - msg = f"Operating system '{os_name}' is not supported." + msg = f"Operating system {os_name!r} is not supported." raise GMTOSError(msg) return libnames @@ -201,7 +201,7 @@ def check_libgmt(libgmt: ctypes.CDLL) -> None: for func in ["Create_Session", "Get_Enum", "Call_Module", "Destroy_Session"]: if not hasattr(libgmt, f"GMT_{func}"): msg = ( - f"Error loading '{libgmt._name}'. Couldn't access function GMT_{func}. " + f"Error loading {libgmt._name!r}. Couldn't access function GMT_{func}. " "Ensure that you have installed an up-to-date GMT version 6 library and " "set the environment variable 'GMT_LIBRARY_PATH' to the directory of " "the GMT 6 library." diff --git a/pygmt/clib/session.py b/pygmt/clib/session.py index 3629f14cd69..6ce70fa4f67 100644 --- a/pygmt/clib/session.py +++ b/pygmt/clib/session.py @@ -283,7 +283,7 @@ def get_enum(self, name: str) -> int: session = None value = c_get_enum(session, name.encode()) if value is None or value == -99999: - msg = f"Constant '{name}' doesn't exist in libgmt." + msg = f"Constant {name!r} doesn't exist in libgmt." raise GMTCLibError(msg) return value @@ -506,7 +506,7 @@ def get_default(self, name: str) -> str: value = ctp.create_string_buffer(4096) status = c_get_default(self.session_pointer, name.encode(), value) if status != 0: - msg = f"Error getting value for '{name}' (error code {status})." + msg = f"Error getting value for {name!r} (error code {status})." raise GMTCLibError(msg) return value.value.decode() @@ -666,7 +666,7 @@ def call_module(self, module: str, args: str | list[str]) -> None: status = c_call_module(self.session_pointer, module.encode(), mode, argv) if status != 0: - msg = f"Module '{module}' failed with status code {status}:\n{self._error_message}" + msg = f"Module {module!r} failed with status code {status}:\n{self._error_message}" raise GMTCLibError(msg) def create_data( @@ -1209,7 +1209,7 @@ def read_data( data, ) if data_ptr is None: - msg = f"Failed to read dataset from '{infile}'." + msg = f"Failed to read dataset from {infile!r}." raise GMTCLibError(msg) return ctp.cast(data_ptr, ctp.POINTER(dtype)) @@ -1280,7 +1280,7 @@ def write_data(self, family, geometry, mode, wesn, output, data) -> None: data, ) if status != 0: - msg = f"Failed to write dataset to '{output}'." + msg = f"Failed to write dataset to {output!r}." raise GMTCLibError(msg) @contextlib.contextmanager @@ -1395,7 +1395,7 @@ def open_virtualfile( finally: status = c_close_virtualfile(self.session_pointer, vfname.encode()) if status != 0: - msg = f"Failed to close virtual file '{vfname}'." + msg = f"Failed to close virtual file {vfname!r}." raise GMTCLibError(msg) @contextlib.contextmanager diff --git a/pygmt/datasets/tile_map.py b/pygmt/datasets/tile_map.py index c55f1a28a52..79dc3a30f31 100644 --- a/pygmt/datasets/tile_map.py +++ b/pygmt/datasets/tile_map.py @@ -148,7 +148,7 @@ def load_tile_map( if crs != _source_crs and not _HAS_RIOXARRAY: msg = ( - f"Package `rioxarray` is required if CRS is not '{_source_crs}'. " + f"Package `rioxarray` is required if CRS is not {_source_crs!r}. " "Please use `python -m pip install rioxarray` or " "`mamba install -c conda-forge rioxarray` to install the package." ) diff --git a/pygmt/figure.py b/pygmt/figure.py index d0038465cf5..136f0008b9b 100644 --- a/pygmt/figure.py +++ b/pygmt/figure.py @@ -232,7 +232,7 @@ def savefig( raise GMTValueError( transparent, description="value for parameter 'transparent'", - reason=f"Transparency unavailable for '{ext}', only for png and kml.", + reason=f"Transparency unavailable for {ext!r}, only for png and kml.", ) if anti_alias: kwargs["Qt"] = 2 diff --git a/pygmt/helpers/decorators.py b/pygmt/helpers/decorators.py index bcc83abb210..8920c0ac408 100644 --- a/pygmt/helpers/decorators.py +++ b/pygmt/helpers/decorators.py @@ -558,7 +558,7 @@ def new_module(*args, **kwargs): elif short_param in kwargs: msg = ( f"Short-form parameter ({short_param}) is not recommended. " - f"Use long-form parameter '{long_alias}' instead." + f"Use long-form parameter {long_alias!r} instead." ) warnings.warn(msg, category=SyntaxWarning, stacklevel=2) @@ -629,7 +629,7 @@ def kwargs_to_strings(**conversions): ... "A module that prints the arguments it received" ... print("{", end="") ... print( - ... ", ".join(f"'{k}': {repr(kwargs[k])}" for k in sorted(kwargs)), + ... ", ".join(f"{k!r}: {kwargs[k]!r}" for k in sorted(kwargs)), ... end="", ... ) ... print("}") @@ -684,7 +684,7 @@ def kwargs_to_strings(**conversions): ... print(offset, end=" ") ... print("{", end="") ... print( - ... ", ".join(f"'{k}': {repr(kwargs[k])}" for k in sorted(kwargs)), + ... ", ".join(f"{k!r}: {kwargs[k]!r}" for k in sorted(kwargs)), ... end="", ... ) ... print("}") @@ -705,7 +705,7 @@ def kwargs_to_strings(**conversions): if fmt not in separators: raise GMTValueError( fmt, - description=f"conversion type for parameter '{arg}'", + description=f"conversion type for parameter {arg!r}", choices=separators.keys(), ) @@ -826,9 +826,9 @@ def new_module(*args, **kwargs): reason=f"{oldname!r} is deprecated and {newname!r} is recommended.", ) msg = ( - f"The '{oldname}' parameter has been deprecated since {deprecate_version}" + f"The {oldname!r} parameter has been deprecated since {deprecate_version}" f" and will be removed in {remove_version}." - f" Please use '{newname}' instead." + f" Please use {newname!r} instead." ) warnings.warn(msg, category=FutureWarning, stacklevel=2) kwargs[newname] = kwargs.pop(oldname) diff --git a/pygmt/helpers/testing.py b/pygmt/helpers/testing.py index eda69f1d634..dad621f71c9 100644 --- a/pygmt/helpers/testing.py +++ b/pygmt/helpers/testing.py @@ -195,4 +195,4 @@ def skip_if_no(package): has_package = True except ImportError: has_package = False - return pytest.mark.skipif(not has_package, reason=f"Could not import '{package}'") + return pytest.mark.skipif(not has_package, reason=f"Could not import {package!r}") diff --git a/pygmt/helpers/utils.py b/pygmt/helpers/utils.py index c2823bb8329..c26b1df85f7 100644 --- a/pygmt/helpers/utils.py +++ b/pygmt/helpers/utils.py @@ -561,7 +561,7 @@ def build_arg_list( # noqa: PLR0912 gmt_args = [] for key, value in kwdict.items(): if len(key) > 2: # Raise an exception for unrecognized options - msg = f"Unrecognized parameter '{key}'." + msg = f"Unrecognized parameter {key!r}." raise GMTInvalidInput(msg) if value is None or value is False: # Exclude arguments that are None or False pass @@ -861,7 +861,7 @@ def sequence_join( # Change size to a list to simplify the checks. size = [size] if isinstance(size, int) else size errmsg = { - "name": f"Parameter '{name}': " if name else "", + "name": f"Parameter {name!r}: " if name else "", "sizes": ", ".join(str(s) for s in size) if size is not None else "", } diff --git a/pygmt/helpers/validators.py b/pygmt/helpers/validators.py index e0044a51dc0..4f7c57c2e92 100644 --- a/pygmt/helpers/validators.py +++ b/pygmt/helpers/validators.py @@ -62,7 +62,7 @@ def validate_output_table_type( ) if output_type != "file" and outfile is not None: msg = ( - f"Changing 'output_type' from '{output_type}' to 'file' since 'outfile' " + f"Changing 'output_type' from {output_type!r} to 'file' since 'outfile' " "parameter is set. Please use output_type='file' to suppress the warning." ) warnings.warn(message=msg, category=RuntimeWarning, stacklevel=2) diff --git a/pygmt/src/_common.py b/pygmt/src/_common.py index 69066e0d26d..c929e586065 100644 --- a/pygmt/src/_common.py +++ b/pygmt/src/_common.py @@ -198,7 +198,7 @@ def __init__( else: # Convention is specified via "convention" and "component". name = f"{convention.upper()}_{component.upper()}" # e.g., "AKI_DC" if name not in _FocalMechanismConventionCode.__members__: - _value = f"convention='{convention}', component='{component}'" + _value = f"convention={convention!r}, component={component!r}" raise GMTValueError(_value, description="focal mechanism convention") self.code = _FocalMechanismConventionCode[name] self._convention = convention diff --git a/pygmt/src/which.py b/pygmt/src/which.py index 4790a3bd510..1b96ac6c61f 100644 --- a/pygmt/src/which.py +++ b/pygmt/src/which.py @@ -83,8 +83,12 @@ def which( match paths.size: case 0: - _fname = "', '".join(fname) if is_nonstr_iter(fname) else fname # type: ignore[arg-type] - msg = f"File(s) '{_fname}' not found." + if is_nonstr_iter(fname): + # Format list as 'a.txt', 'b.txt' + _fname = "', '".join(fname) # type: ignore[arg-type] + msg = f"File(s) '{_fname}' not found." + else: + msg = f"File(s) {fname!r} not found." raise FileNotFoundError(msg) case 1: return paths[0] diff --git a/pygmt/tests/test_clib_loading.py b/pygmt/tests/test_clib_loading.py index d56b4ce8d64..9421546ae5f 100644 --- a/pygmt/tests/test_clib_loading.py +++ b/pygmt/tests/test_clib_loading.py @@ -37,13 +37,19 @@ def __str__(self): """ return self._name + def __repr__(self): + """ + Return repr representation to match how real paths are formatted with !r. + """ + return repr(self._name) + def test_check_libgmt(): """ Make sure check_libgmt fails when given a bogus library. """ libgmt = FakedLibGMT("/path/to/libgmt.so") - msg = rf"Error loading '{libgmt}'. Couldn't access function GMT_Create_Session." + msg = rf"Error loading {libgmt!r}. Couldn't access function GMT_Create_Session." with pytest.raises(GMTCLibError, match=msg): check_libgmt(libgmt) @@ -125,7 +131,7 @@ def _mock_ctypes_cdll_return(self, libname): if isinstance(libname, str): # libname is an invalid library path in string type, # raise OSError like the original ctypes.CDLL - msg = f"Unable to find '{libname}'." + msg = f"Unable to find {libname!r}." raise OSError(msg) # libname is a loaded GMT library return self.loaded_libgmt @@ -147,10 +153,10 @@ def test_two_broken_libraries(self): """ lib_fullnames = [self.faked_libgmt1, self.faked_libgmt2] msg_regex = ( - rf"Error loading GMT shared library at '{self.faked_libgmt1._name}'.\n" - rf"Error loading '{self.faked_libgmt1._name}'. Couldn't access.*\n" - rf"Error loading GMT shared library at '{self.faked_libgmt2._name}'.\n" - rf"Error loading '{self.faked_libgmt2._name}'. Couldn't access.*" + rf"Error loading GMT shared library at {self.faked_libgmt1._name!r}.\n" + rf"Error loading {self.faked_libgmt1._name!r}. Couldn't access.*\n" + rf"Error loading GMT shared library at {self.faked_libgmt2._name!r}.\n" + rf"Error loading {self.faked_libgmt2._name!r}. Couldn't access.*" ) with pytest.raises(GMTCLibNotFoundError, match=msg_regex): load_libgmt(lib_fullnames=lib_fullnames) @@ -165,10 +171,10 @@ def test_load_brokenlib_invalidpath(self): """ lib_fullnames = [self.faked_libgmt1, self.invalid_path] msg_regex = ( - rf"Error loading GMT shared library at '{self.faked_libgmt1._name}'.\n" - rf"Error loading '{self.faked_libgmt1._name}'. Couldn't access.*\n" - rf"Error loading GMT shared library at '{self.invalid_path}'.\n" - rf"Unable to find '{self.invalid_path}'" + rf"Error loading GMT shared library at {self.faked_libgmt1._name!r}.\n" + rf"Error loading {self.faked_libgmt1._name!r}. Couldn't access.*\n" + rf"Error loading GMT shared library at {self.invalid_path!r}.\n" + rf"Unable to find {self.invalid_path!r}" ) with pytest.raises(GMTCLibNotFoundError, match=msg_regex): load_libgmt(lib_fullnames=lib_fullnames)