Skip to content

Commit 8472d86

Browse files
committed
Use the new exception
1 parent 181475c commit 8472d86

29 files changed

+155
-143
lines changed

pygmt/clib/session.py

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,12 @@
2424
)
2525
from pygmt.clib.loading import get_gmt_version, load_libgmt
2626
from pygmt.datatypes import _GMT_DATASET, _GMT_GRID, _GMT_IMAGE
27-
from pygmt.exceptions import GMTCLibError, GMTCLibNoSessionError, GMTInvalidInput
27+
from pygmt.exceptions import (
28+
GMTCLibError,
29+
GMTCLibNoSessionError,
30+
GMTInvalidInput,
31+
GMTValueError,
32+
)
2833
from pygmt.helpers import (
2934
_validate_data_input,
3035
data_kind,
@@ -560,11 +565,13 @@ def get_common(self, option: str) -> bool | int | float | np.ndarray:
560565
... lib.get_common("A")
561566
Traceback (most recent call last):
562567
...
563-
pygmt.exceptions.GMTInvalidInput: Unknown GMT common option flag 'A'.
568+
pygmt.exceptions.GMTValueError: Invalid GMT common option: 'A'. Expected ...
564569
"""
565-
if option not in "BIJRUVXYabfghinoprst:":
566-
msg = f"Unknown GMT common option flag '{option}'."
567-
raise GMTInvalidInput(msg)
570+
valid_options = "BIJRUVXYabfghinoprst:"
571+
if option not in valid_options:
572+
raise GMTValueError(
573+
option, description="GMT common option", choices=valid_options
574+
)
568575

569576
c_get_common = self.get_libgmt_func(
570577
"GMT_Get_Common",
@@ -847,15 +854,15 @@ def _parse_constant(
847854
their values are added.
848855
849856
If no valid modifiers are given, then will assume that modifiers are not
850-
allowed. In this case, will raise a :class:`pygmt.exceptions.GMTInvalidInput`
857+
allowed. In this case, will raise a :class:`pygmt.exceptions.GMTValueError`
851858
exception if given a modifier.
852859
853860
Parameters
854861
----------
855862
constant
856863
The name of a valid GMT API constant, with an optional modifier.
857864
valid
858-
A list of valid values for the constant. Will raise a GMTInvalidInput
865+
A list of valid values for the constant. Will raise a GMTValueError
859866
exception if the given value is not in the list.
860867
valid_modifiers
861868
A list of valid modifiers that can be added to the constant. If ``None``,
@@ -866,28 +873,23 @@ def _parse_constant(
866873
nmodifiers = len(parts) - 1
867874

868875
if name not in valid:
869-
msg = f"Invalid constant name '{name}'. Must be one of {valid}."
870-
raise GMTInvalidInput(msg)
876+
raise GMTValueError(name, description="constant name", choices=valid)
871877

872878
match nmodifiers:
873879
case 1 if valid_modifiers is None:
874-
msg = (
875-
f"Constant modifiers are not allowed since valid values "
876-
f"were not given: '{constant}'."
880+
raise GMTValueError(
881+
constant,
882+
reason="Constant modifiers are not allowed since valid values were not given.",
877883
)
878-
raise GMTInvalidInput(msg)
879884
case 1 if valid_modifiers is not None and parts[1] not in valid_modifiers:
880-
msg = (
881-
f"Invalid constant modifier '{parts[1]}'. "
882-
f"Must be one of {valid_modifiers}."
885+
raise GMTValueError(
886+
parts[1], description="constant modifier", choices=valid_modifiers
883887
)
884-
raise GMTInvalidInput(msg)
885888
case n if n > 1:
886-
msg = (
887-
f"Only one modifier is allowed in constants, "
888-
f"{nmodifiers} given: '{constant}'."
889+
raise GMTValueError(
890+
constant,
891+
reason=f"Only one modifier is allowed in constants but {nmodifiers} given.",
889892
)
890-
raise GMTInvalidInput(msg)
891893

892894
integer_value = sum(self[part] for part in parts)
893895
return integer_value

pygmt/datasets/earth_magnetic_anomaly.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
import xarray as xr
1212
from pygmt.datasets.load_remote_dataset import _load_remote_dataset
13-
from pygmt.exceptions import GMTInvalidInput
13+
from pygmt.exceptions import GMTValueError
1414

1515
__doctest_skip__ = ["load_earth_magnetic_anomaly"]
1616

@@ -135,11 +135,11 @@ def load_earth_magnetic_anomaly(
135135
"wdmam": "earth_wdmam",
136136
}.get(data_source)
137137
if prefix is None:
138-
msg = (
139-
f"Invalid earth magnetic anomaly data source '{data_source}'. "
140-
"Valid values are 'emag2', 'emag2_4km', and 'wdmam'."
138+
raise GMTValueError(
139+
data_source,
140+
description="earth magnetic anomaly data source",
141+
choices=["emag2", "emag2_4km", "wdmam"],
141142
)
142-
raise GMTInvalidInput(msg)
143143
grid = _load_remote_dataset(
144144
name="earth_wdmam" if data_source == "wdmam" else "earth_mag",
145145
prefix=prefix,

pygmt/datasets/earth_relief.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
import xarray as xr
1212
from pygmt.datasets.load_remote_dataset import _load_remote_dataset
13-
from pygmt.exceptions import GMTInvalidInput
13+
from pygmt.exceptions import GMTInvalidInput, GMTValueError
1414

1515
__doctest_skip__ = ["load_earth_relief"]
1616

@@ -154,11 +154,11 @@ def load_earth_relief(
154154
"synbath": "earth_synbath",
155155
}.get(data_source)
156156
if prefix is None:
157-
msg = (
158-
f"Invalid earth relief data source '{data_source}'. "
159-
"Valid values are 'igpp', 'gebco', 'gebcosi', and 'synbath'."
157+
raise GMTValueError(
158+
data_source,
159+
description="earth relief data source",
160+
choices=["igpp", "gebco", "gebcosi", "synbath"],
160161
)
161-
raise GMTInvalidInput(msg)
162162
# Use SRTM or not.
163163
if use_srtm and resolution in land_only_srtm_resolutions:
164164
if data_source != "igpp":

pygmt/datasets/load_remote_dataset.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from typing import Any, Literal, NamedTuple
88

99
import xarray as xr
10-
from pygmt.exceptions import GMTInvalidInput
10+
from pygmt.exceptions import GMTInvalidInput, GMTValueError
1111

1212
with contextlib.suppress(ImportError):
1313
# rioxarray is needed to register the rio accessor
@@ -546,11 +546,11 @@ def _load_remote_dataset(
546546

547547
# Check resolution
548548
if resolution not in dataset.resolutions:
549-
msg = (
550-
f"Invalid resolution '{resolution}' for {dataset.description} dataset. "
551-
f"Available resolutions are: {', '.join(dataset.resolutions)}."
549+
raise GMTValueError(
550+
value=resolution,
551+
description=f"resolution for {dataset.description} dataset",
552+
choices=dataset.resolutions.keys(),
552553
)
553-
raise GMTInvalidInput(msg)
554554
resinfo = dataset.resolutions[resolution]
555555

556556
# Check registration
@@ -559,13 +559,15 @@ def _load_remote_dataset(
559559
# Use gridline registration unless only pixel registration is available
560560
reg = "g" if "gridline" in resinfo.registrations else "p"
561561
case x if x not in resinfo.registrations:
562-
msg = (
563-
f"Invalid grid registration '{registration}' for the {resolution} "
564-
f"{dataset.description} dataset. Should be either 'pixel', 'gridline' "
565-
"or None. Default is None, where a gridline-registered grid is "
566-
"returned unless only the pixel-registered grid is available."
562+
raise GMTValueError(
563+
registration,
564+
description=f"grid registration for the {resolution} {dataset.description} dataset",
565+
choices=[*resinfo.registrations, None],
566+
reason=(
567+
"Default is None, where a gridline-registered grid is returned "
568+
"unless only the pixel-registered grid is available."
569+
),
567570
)
568-
raise GMTInvalidInput(msg)
569571
case _:
570572
reg = registration[0]
571573

pygmt/datasets/samples.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import pandas as pd
99
import xarray as xr
10-
from pygmt.exceptions import GMTInvalidInput
10+
from pygmt.exceptions import GMTValueError
1111
from pygmt.src import which
1212

1313

@@ -346,6 +346,5 @@ def load_sample_data(
346346
>>> data = load_sample_data("bathymetry")
347347
""" # noqa: W505
348348
if name not in datasets:
349-
msg = f"Invalid dataset name '{name}'."
350-
raise GMTInvalidInput(msg)
349+
raise GMTValueError(name, choices=datasets.keys(), description="dataset name")
351350
return datasets[name].func()

pygmt/figure.py

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
import numpy as np
2222
from pygmt.clib import Session
23-
from pygmt.exceptions import GMTInvalidInput
23+
from pygmt.exceptions import GMTInvalidInput, GMTValueError
2424
from pygmt.helpers import launch_external_viewer, unique_name
2525

2626

@@ -234,11 +234,15 @@ def savefig(
234234
case "kml": # KML
235235
kwargs["W"] = "+k"
236236
case "ps":
237-
msg = "Extension '.ps' is not supported. Use '.eps' or '.pdf' instead."
238-
raise GMTInvalidInput(msg)
237+
raise GMTValueError(
238+
ext,
239+
description="file extension",
240+
reason="Extension '.ps' is not supported. Use '.eps' or '.pdf' instead.",
241+
)
239242
case ext if ext not in fmts:
240-
msg = f"Unknown extension '.{ext}'."
241-
raise GMTInvalidInput(msg)
243+
raise GMTValueError(
244+
ext, description="file extension", choices=fmts.keys()
245+
)
242246

243247
if transparent and ext not in {"kml", "png"}:
244248
msg = f"Transparency unavailable for '{ext}', only for png and kml."
@@ -249,8 +253,12 @@ def savefig(
249253

250254
if worldfile:
251255
if ext in {"eps", "kml", "pdf", "tiff"}:
252-
msg = f"Saving a world file is not supported for '{ext}' format."
253-
raise GMTInvalidInput(msg)
256+
raise GMTValueError(
257+
ext,
258+
description="file extension",
259+
choices=["eps", "kml", "pdf", "tiff"],
260+
reason="Saving a world file is not supported for this format.",
261+
)
254262
kwargs["W"] = True
255263

256264
# pytest-mpl v0.17.0 added the "metadata" parameter to Figure.savefig, which is
@@ -358,11 +366,11 @@ def show(
358366
case "none":
359367
pass # Do nothing
360368
case _:
361-
msg = (
362-
f"Invalid display method '{method}'. "
363-
"Valid values are 'external', 'notebook', 'none' or None."
369+
raise GMTValueError(
370+
method,
371+
description="display method",
372+
choices=["external", "notebook", "none", None],
364373
)
365-
raise GMTInvalidInput(msg)
366374

367375
@overload
368376
def _preview(
@@ -494,8 +502,8 @@ def set_display(method: Literal["external", "notebook", "none", None] = None) ->
494502
case None:
495503
SHOW_CONFIG["method"] = _get_default_display_method()
496504
case _:
497-
msg = (
498-
f"Invalid display method '{method}'. "
499-
"Valid values are 'external', 'notebook', 'none' or None."
505+
raise GMTValueError(
506+
method,
507+
description="display method",
508+
choices=["external", "notebook", "none", None],
500509
)
501-
raise GMTInvalidInput(msg)

pygmt/helpers/decorators.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from inspect import Parameter, signature
1313

1414
import numpy as np
15-
from pygmt.exceptions import GMTInvalidInput
15+
from pygmt.exceptions import GMTInvalidInput, GMTValueError
1616
from pygmt.helpers.utils import is_nonstr_iter
1717

1818
COMMON_DOCSTRINGS = {
@@ -732,8 +732,11 @@ def kwargs_to_strings(**conversions):
732732

733733
for arg, fmt in conversions.items():
734734
if fmt not in separators:
735-
msg = f"Invalid conversion type '{fmt}' for argument '{arg}'."
736-
raise GMTInvalidInput(msg)
735+
raise GMTValueError(
736+
fmt,
737+
description=f"conversion type for parameter '{arg}'",
738+
choices=separators.keys(),
739+
)
737740

738741
# Make the actual decorator function
739742
def converter(module_func):

pygmt/src/_common.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from pathlib import Path
88
from typing import Any, ClassVar, Literal
99

10-
from pygmt.exceptions import GMTInvalidInput
10+
from pygmt.exceptions import GMTInvalidInput, GMTValueError
1111
from pygmt.src.which import which
1212

1313

@@ -115,12 +115,12 @@ class _FocalMechanismConvention:
115115
>>> conv = _FocalMechanismConvention(convention="invalid")
116116
Traceback (most recent call last):
117117
...
118-
pygmt.exceptions.GMTInvalidInput: Invalid focal mechanism ...'.
118+
pygmt.exceptions.GMTValueError: Invalid focal mechanism convention: ...
119119
120120
>>> conv = _FocalMechanismConvention("mt", component="invalid")
121121
Traceback (most recent call last):
122122
...
123-
pygmt.exceptions.GMTInvalidInput: Invalid focal mechanism ...'.
123+
pygmt.exceptions.GMTValueError: Invalid focal mechanism convention: ...
124124
125125
>>> _FocalMechanismConvention.from_params(["strike", "dip", "rake"])
126126
Traceback (most recent call last):
@@ -198,11 +198,8 @@ def __init__(
198198
else: # Convention is specified via "convention" and "component".
199199
name = f"{convention.upper()}_{component.upper()}" # e.g., "AKI_DC"
200200
if name not in _FocalMechanismConventionCode.__members__:
201-
msg = (
202-
"Invalid focal mechanism convention with "
203-
f"convention='{convention}' and component='{component}'."
204-
)
205-
raise GMTInvalidInput(msg)
201+
_value = f"convention='{convention}', component='{component}'"
202+
raise GMTValueError(_value, description="focal mechanism convention")
206203
self.code = _FocalMechanismConventionCode[name]
207204
self._convention = convention
208205

@@ -287,7 +284,7 @@ def _parse_coastline_resolution(
287284
>>> _parse_coastline_resolution("invalid")
288285
Traceback (most recent call last):
289286
...
290-
pygmt.exceptions.GMTInvalidInput: Invalid resolution: 'invalid'. Valid values ...
287+
pygmt...GMTValueError: Invalid .... Expected ....
291288
"""
292289
if resolution is None:
293290
return None
@@ -300,7 +297,6 @@ def _parse_coastline_resolution(
300297
if resolution in {_res[0] for _res in _valid_res}: # Short-form arguments.
301298
return resolution # type: ignore[return-value]
302299

303-
msg = (
304-
f"Invalid resolution: '{resolution}'. Valid values are {', '.join(_valid_res)}."
300+
raise GMTValueError(
301+
resolution, choices=_valid_res, description="GSHHG coastline resolution"
305302
)
306-
raise GMTInvalidInput(msg)

pygmt/src/grdcut.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import xarray as xr
88
from pygmt._typing import PathLike
99
from pygmt.clib import Session
10-
from pygmt.exceptions import GMTInvalidInput
10+
from pygmt.exceptions import GMTInvalidInput, GMTValueError
1111
from pygmt.helpers import (
1212
build_arg_list,
1313
data_kind,
@@ -113,8 +113,7 @@ def grdcut(
113113
>>> new_grid = pygmt.grdcut(grid=grid, region=[12, 15, 21, 24])
114114
"""
115115
if kind not in {"grid", "image"}:
116-
msg = f"Invalid raster kind: '{kind}'. Valid values are 'grid' and 'image'."
117-
raise GMTInvalidInput(msg)
116+
raise GMTValueError(kind, description="raster kind", choices=["grid", "image"])
118117

119118
# Determine the output data kind based on the input data kind.
120119
match inkind := data_kind(grid):

pygmt/src/psconvert.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from pathlib import Path
66

77
from pygmt.clib import Session
8-
from pygmt.exceptions import GMTInvalidInput
8+
from pygmt.exceptions import GMTValueError
99
from pygmt.helpers import build_arg_list, fmt_docstring, kwargs_to_strings, use_alias
1010

1111

@@ -115,8 +115,11 @@ def psconvert(self, **kwargs):
115115

116116
prefix = kwargs.get("F")
117117
if prefix in {"", None, False, True}:
118-
msg = "The 'prefix' parameter must be specified with a valid value."
119-
raise GMTInvalidInput(msg)
118+
raise GMTValueError(
119+
prefix,
120+
description="output file name",
121+
reason="Parameter 'prefix' can't be None, bool, or an empty string.",
122+
)
120123

121124
# Check if the parent directory exists
122125
prefix_path = Path(prefix).parent

0 commit comments

Comments
 (0)