Skip to content

Commit 26468b2

Browse files
committed
Use the new exception
1 parent a3869ee commit 26468b2

23 files changed

+135
-118
lines changed

pygmt/clib/session.py

Lines changed: 26 additions & 20 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,15 @@ 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'.
564-
"""
565-
if option not in "BIJRUVXYabfghinoprst:":
566-
msg = f"Unknown GMT common option flag '{option}'."
567-
raise GMTInvalidInput(msg)
568+
pygmt.exceptions.GMTValueError: Invalid GMT common option: 'A'. Expecetd ...
569+
"""
570+
valid_options = "BIJRUVXYabfghinoprst:"
571+
if option not in valid_options:
572+
raise GMTValueError(
573+
option,
574+
description="GMT common option flag",
575+
choices=valid_options,
576+
)
568577

569578
c_get_common = self.get_libgmt_func(
570579
"GMT_Get_Common",
@@ -866,28 +875,25 @@ def _parse_constant(
866875
nmodifiers = len(parts) - 1
867876

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

872880
match nmodifiers:
873881
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}'."
882+
raise GMTValueError(
883+
constant,
884+
reason="Constant modifiers are not allowed since valid values were not given",
877885
)
878-
raise GMTInvalidInput(msg)
879886
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}."
887+
raise GMTValueError(
888+
parts[1],
889+
description="constant modifier",
890+
choices=valid_modifiers,
883891
)
884-
raise GMTInvalidInput(msg)
885892
case n if n > 1:
886-
msg = (
887-
f"Only one modifier is allowed in constants, "
888-
f"{nmodifiers} given: '{constant}'."
893+
raise GMTValueError(
894+
constant,
895+
reason=f"Only one modifier is allowed in constants but {nmodifiers} given",
889896
)
890-
raise GMTInvalidInput(msg)
891897

892898
integer_value = sum(self[part] for part in parts)
893899
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.keys(), 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: 24 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,16 @@ 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+
choices=list(fmts.keys()),
241+
reason="Extension '.ps' is not supported. Use '.eps' or '.pdf' instead",
242+
)
239243
case ext if ext not in fmts:
240-
msg = f"Unknown extension '.{ext}'."
241-
raise GMTInvalidInput(msg)
244+
raise GMTValueError(
245+
ext, description="file extension", choices=list(fmts.keys())
246+
)
242247

243248
if transparent and ext not in {"kml", "png"}:
244249
msg = f"Transparency unavailable for '{ext}', only for png and kml."
@@ -249,8 +254,12 @@ def savefig(
249254

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

256265
# pytest-mpl v0.17.0 added the "metadata" parameter to Figure.savefig, which is
@@ -358,11 +367,11 @@ def show(
358367
case "none":
359368
pass # Do nothing
360369
case _:
361-
msg = (
362-
f"Invalid display method '{method}'. "
363-
"Valid values are 'external', 'notebook', 'none' or None."
370+
raise GMTValueError(
371+
method,
372+
description="display method",
373+
choices=["external", "notebook", "none", None],
364374
)
365-
raise GMTInvalidInput(msg)
366375

367376
@overload
368377
def _preview(
@@ -494,8 +503,8 @@ def set_display(method: Literal["external", "notebook", "none", None] = None) ->
494503
case None:
495504
SHOW_CONFIG["method"] = _get_default_display_method()
496505
case _:
497-
msg = (
498-
f"Invalid display method '{method}'. "
499-
"Valid values are 'external', 'notebook', 'none' or None."
506+
raise GMTValueError(
507+
method,
508+
description="display method",
509+
choices=["external", "notebook", "none", None],
500510
)
501-
raise GMTInvalidInput(msg)

pygmt/src/_common.py

Lines changed: 4 additions & 5 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

@@ -287,7 +287,7 @@ def _parse_coastline_resolution(
287287
>>> _parse_coastline_resolution("invalid")
288288
Traceback (most recent call last):
289289
...
290-
pygmt.exceptions.GMTInvalidInput: Invalid resolution: 'invalid'. Valid values ...
290+
pygmt...GMTValueError: Invalid .... Expected ....
291291
"""
292292
if resolution is None:
293293
return None
@@ -300,7 +300,6 @@ def _parse_coastline_resolution(
300300
if resolution in {_res[0] for _res in _valid_res}: # Short-form arguments.
301301
return resolution # type: ignore[return-value]
302302

303-
msg = (
304-
f"Invalid resolution: '{resolution}'. Valid values are {', '.join(_valid_res)}."
303+
raise GMTValueError(
304+
resolution, choices=_valid_res, description="GSHHG coastline resolution"
305305
)
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/solar.py

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

77
import pandas as pd
88
from pygmt.clib import Session
9-
from pygmt.exceptions import GMTInvalidInput
9+
from pygmt.exceptions import GMTInvalidInput, GMTValueError
1010
from pygmt.helpers import build_arg_list, fmt_docstring, kwargs_to_strings, use_alias
1111

1212
__doctest_skip__ = ["solar"]
@@ -103,11 +103,11 @@ def solar(
103103

104104
valid_terminators = ["day_night", "civil", "nautical", "astronomical"]
105105
if terminator not in valid_terminators and terminator not in "dcna":
106-
msg = (
107-
f"Unrecognized solar terminator type '{terminator}'. "
108-
f"Valid values are {valid_terminators}."
106+
raise GMTValueError(
107+
terminator,
108+
description="solar terminator type",
109+
choices=valid_terminators,
109110
)
110-
raise GMTInvalidInput(msg)
111111
kwargs["T"] = terminator[0]
112112
if terminator_datetime:
113113
try:

pygmt/tests/test_clib.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from pygmt.exceptions import (
1414
GMTCLibError,
1515
GMTCLibNoSessionError,
16-
GMTInvalidInput,
16+
GMTValueError,
1717
GMTVersionError,
1818
)
1919

@@ -170,7 +170,7 @@ def test_parse_constant_fails():
170170
"NOT_A_PROPER_FAMILY|ALSO_INVALID",
171171
]
172172
for test_case in test_cases:
173-
with pytest.raises(GMTInvalidInput):
173+
with pytest.raises(GMTValueError):
174174
lib._parse_constant(test_case, valid=FAMILIES, valid_modifiers=VIAS)
175175

176176
# Should also fail if not given valid modifiers but is using them anyway.
@@ -179,7 +179,7 @@ def test_parse_constant_fails():
179179
"GMT_IS_DATASET|GMT_VIA_MATRIX", valid=FAMILIES, valid_modifiers=VIAS
180180
)
181181
# But this shouldn't.
182-
with pytest.raises(GMTInvalidInput):
182+
with pytest.raises(GMTValueError):
183183
lib._parse_constant(
184184
"GMT_IS_DATASET|GMT_VIA_MATRIX", valid=FAMILIES, valid_modifiers=None
185185
)

pygmt/tests/test_clib_create_data.py

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

55
import pytest
66
from pygmt import clib
7-
from pygmt.exceptions import GMTCLibError, GMTInvalidInput
7+
from pygmt.exceptions import GMTCLibError, GMTValueError
88
from pygmt.tests.test_clib import mock
99

1010

@@ -64,7 +64,7 @@ def test_create_data_fails():
6464
Check that create_data raises exceptions for invalid input and output.
6565
"""
6666
# Passing in invalid mode
67-
with pytest.raises(GMTInvalidInput):
67+
with pytest.raises(GMTValueError):
6868
with clib.Session() as lib:
6969
lib.create_data(
7070
family="GMT_IS_DATASET",
@@ -75,7 +75,7 @@ def test_create_data_fails():
7575
inc=[0.1, 0.2],
7676
)
7777
# Passing in invalid geometry
78-
with pytest.raises(GMTInvalidInput):
78+
with pytest.raises(GMTValueError):
7979
with clib.Session() as lib:
8080
lib.create_data(
8181
family="GMT_IS_GRID",

0 commit comments

Comments
 (0)