Skip to content
6 changes: 3 additions & 3 deletions pygmt/clib/conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
[
Expand Down
6 changes: 3 additions & 3 deletions pygmt/clib/loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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."
Expand Down
12 changes: 6 additions & 6 deletions pygmt/clib/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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))

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pygmt/datasets/tile_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."
)
Expand Down
2 changes: 1 addition & 1 deletion pygmt/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 6 additions & 6 deletions pygmt/helpers/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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("}")
Expand Down Expand Up @@ -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("}")
Expand All @@ -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(),
)

Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pygmt/helpers/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
4 changes: 2 additions & 2 deletions pygmt/helpers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 "",
}

Expand Down
2 changes: 1 addition & 1 deletion pygmt/helpers/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pygmt/src/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions pygmt/src/which.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
26 changes: 16 additions & 10 deletions pygmt/tests/test_clib_loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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)
Expand Down
Loading