Skip to content

Commit a2b9724

Browse files
seismanweiji14
andauthored
TYP: Add PathLike and TableLike types for type hints and remove the table-like placeholder (#3920)
Co-authored-by: Wei Ji <[email protected]>
1 parent 99a6340 commit a2b9724

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+229
-116
lines changed

pygmt/_typing.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,13 @@
44

55
import contextlib
66
import importlib
7+
import os
78
from collections.abc import Sequence
89
from typing import Literal
910

1011
import numpy as np
12+
import pandas as pd
13+
import xarray as xr
1114

1215
# Anchor codes
1316
AnchorCode = Literal["TL", "TC", "TR", "ML", "MC", "MR", "BL", "BC", "BR"]
@@ -16,3 +19,9 @@
1619
StringArrayTypes = Sequence[str] | np.ndarray
1720
with contextlib.suppress(ImportError):
1821
StringArrayTypes |= importlib.import_module(name="pyarrow").StringArray
22+
23+
# PathLike and TableLike types
24+
PathLike = str | os.PathLike
25+
TableLike = dict | np.ndarray | pd.DataFrame | xr.Dataset
26+
with contextlib.suppress(ImportError):
27+
TableLike |= importlib.import_module(name="geopandas").GeoDataFrame

pygmt/clib/session.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1772,7 +1772,7 @@ def virtualfile_in(
17721772
check_kind : str or None
17731773
Used to validate the type of data that can be passed in. Choose
17741774
from 'raster', 'vector', or None. Default is None (no validation).
1775-
data : str or pathlib.Path or xarray.DataArray or {table-like} or dict or None
1775+
data
17761776
Any raster or vector data format. This could be a file name or
17771777
path, a raster grid, a vector matrix/arrays, or other supported
17781778
data input.

pygmt/figure.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44

55
import base64
66
import os
7-
from pathlib import Path, PurePath
7+
from pathlib import Path
88
from tempfile import TemporaryDirectory
99
from typing import Literal, overload
1010

11+
from pygmt._typing import PathLike
12+
1113
try:
1214
import IPython
1315

@@ -137,7 +139,7 @@ def region(self) -> np.ndarray:
137139

138140
def savefig(
139141
self,
140-
fname: str | PurePath,
142+
fname: PathLike,
141143
transparent: bool = False,
142144
crop: bool = True,
143145
anti_alias: bool = True,

pygmt/helpers/decorators.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@
141141
- **+p**: specify that the current value minus the previous
142142
value must exceed *gap* for a break to be imposed.""",
143143
"grid": r"""
144-
grid : str or xarray.DataArray
144+
grid
145145
Name of the input grid file or the grid loaded as a
146146
:class:`xarray.DataArray` object.
147147
@@ -408,7 +408,7 @@ def fmt_docstring(module_func):
408408
...
409409
... Parameters
410410
... ----------
411-
... data : str, {table-like}
411+
... data
412412
... Pass in either a file name to an ASCII data table, a 2-D
413413
... {table-classes}.
414414
... {region}
@@ -423,7 +423,7 @@ def fmt_docstring(module_func):
423423
<BLANKLINE>
424424
Parameters
425425
----------
426-
data : str, numpy.ndarray, pandas.DataFrame, xarray.Dataset, or geo...
426+
data
427427
Pass in either a file name to an ASCII data table, a 2-D
428428
:class:`numpy.ndarray`, a :class:`pandas.DataFrame`, an
429429
:class:`xarray.Dataset` made up of 1-D :class:`xarray.DataArray`
@@ -455,9 +455,6 @@ def fmt_docstring(module_func):
455455
aliases.append(f" - {arg} = {alias}")
456456
filler_text["aliases"] = "\n".join(aliases)
457457

458-
filler_text["table-like"] = (
459-
"numpy.ndarray, pandas.DataFrame, xarray.Dataset, or geopandas.GeoDataFrame"
460-
)
461458
filler_text["table-classes"] = (
462459
":class:`numpy.ndarray`, a :class:`pandas.DataFrame`, an\n"
463460
" :class:`xarray.Dataset` made up of 1-D :class:`xarray.DataArray`\n"

pygmt/helpers/utils.py

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

55
import io
66
import os
7-
import pathlib
87
import shutil
98
import string
109
import subprocess
@@ -17,6 +16,7 @@
1716
from typing import Any, Literal
1817

1918
import xarray as xr
19+
from pygmt._typing import PathLike
2020
from pygmt.encodings import charset
2121
from pygmt.exceptions import GMTInvalidInput
2222

@@ -387,10 +387,10 @@ def data_kind(
387387
match data:
388388
case None if required: # No data provided and required=True.
389389
kind = "empty"
390-
case str() | pathlib.PurePath(): # One file.
390+
case str() | os.PathLike(): # One file.
391391
kind = "file"
392392
case list() | tuple() if all(
393-
isinstance(_file, str | pathlib.PurePath) for _file in data
393+
isinstance(_file, str | os.PathLike) for _file in data
394394
): # A list/tuple of files.
395395
kind = "file"
396396
case io.StringIO():
@@ -482,8 +482,8 @@ def non_ascii_to_octal(argstr: str, encoding: Encoding = "ISOLatin1+") -> str:
482482
def build_arg_list( # noqa: PLR0912
483483
kwdict: dict[str, Any],
484484
confdict: Mapping[str, Any] | None = None,
485-
infile: str | pathlib.PurePath | Sequence[str | pathlib.PurePath] | None = None,
486-
outfile: str | pathlib.PurePath | None = None,
485+
infile: PathLike | Sequence[PathLike] | None = None,
486+
outfile: PathLike | None = None,
487487
) -> list[str]:
488488
r"""
489489
Convert keyword dictionaries and input/output files into a list of GMT arguments.
@@ -581,19 +581,19 @@ def build_arg_list( # noqa: PLR0912
581581
gmt_args.extend(f"--{key}={value}" for key, value in confdict.items())
582582

583583
if infile: # infile can be a single file or a list of files
584-
if isinstance(infile, str | pathlib.PurePath):
585-
gmt_args = [str(infile), *gmt_args]
584+
if isinstance(infile, str | os.PathLike):
585+
gmt_args = [os.fspath(infile), *gmt_args]
586586
else:
587-
gmt_args = [str(_file) for _file in infile] + gmt_args
587+
gmt_args = [os.fspath(_file) for _file in infile] + gmt_args
588588
if outfile is not None:
589589
if (
590-
not isinstance(outfile, str | pathlib.PurePath)
591-
or str(outfile) in {"", ".", ".."}
592-
or str(outfile).endswith(("/", "\\"))
590+
not isinstance(outfile, str | os.PathLike)
591+
or os.fspath(outfile) in {"", ".", ".."}
592+
or os.fspath(outfile).endswith(("/", "\\"))
593593
):
594594
msg = f"Invalid output file name '{outfile}'."
595595
raise GMTInvalidInput(msg)
596-
gmt_args.append(f"->{outfile}")
596+
gmt_args.append(f"->{os.fspath(outfile)}")
597597
return gmt_args
598598

599599

@@ -632,7 +632,7 @@ def is_nonstr_iter(value: Any) -> bool:
632632
return isinstance(value, Iterable) and not isinstance(value, str)
633633

634634

635-
def launch_external_viewer(fname: str, waiting: float = 0) -> None:
635+
def launch_external_viewer(fname: PathLike, waiting: float = 0) -> None:
636636
"""
637637
Open a file in an external viewer program.
638638

pygmt/helpers/validators.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,12 @@
55
import warnings
66
from typing import Literal
77

8+
from pygmt._typing import PathLike
89
from pygmt.exceptions import GMTInvalidInput
910

1011

1112
def validate_output_table_type(
12-
output_type: Literal["pandas", "numpy", "file"], outfile: str | None = None
13+
output_type: Literal["pandas", "numpy", "file"], outfile: PathLike | None = None
1314
) -> Literal["pandas", "numpy", "file"]:
1415
"""
1516
Check if the ``output_type`` and ``outfile`` parameters are valid.

pygmt/src/binstats.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44

55
import xarray as xr
6+
from pygmt._typing import PathLike, TableLike
67
from pygmt.clib import Session
78
from pygmt.helpers import build_arg_list, fmt_docstring, kwargs_to_strings, use_alias
89

@@ -24,7 +25,9 @@
2425
r="registration",
2526
)
2627
@kwargs_to_strings(I="sequence", R="sequence", i="sequence_comma")
27-
def binstats(data, outgrid: str | None = None, **kwargs) -> xr.DataArray | None:
28+
def binstats(
29+
data: PathLike | TableLike, outgrid: PathLike | None = None, **kwargs
30+
) -> xr.DataArray | None:
2831
r"""
2932
Bin spatial data and determine statistics per bin.
3033
@@ -42,7 +45,7 @@ def binstats(data, outgrid: str | None = None, **kwargs) -> xr.DataArray | None:
4245
4346
Parameters
4447
----------
45-
data : str, {table-like}
48+
data
4649
A file name of an ASCII data table or a 2-D {table-classes}.
4750
{outgrid}
4851
statistic : str

pygmt/src/blockm.py

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

77
import numpy as np
88
import pandas as pd
9+
from pygmt._typing import PathLike, TableLike
910
from pygmt.clib import Session
1011
from pygmt.helpers import (
1112
build_arg_list,
@@ -87,12 +88,12 @@ def _blockm(
8788
)
8889
@kwargs_to_strings(I="sequence", R="sequence", i="sequence_comma", o="sequence_comma")
8990
def blockmean(
90-
data=None,
91+
data: PathLike | TableLike | None = None,
9192
x=None,
9293
y=None,
9394
z=None,
9495
output_type: Literal["pandas", "numpy", "file"] = "pandas",
95-
outfile: str | None = None,
96+
outfile: PathLike | None = None,
9697
**kwargs,
9798
) -> pd.DataFrame | np.ndarray | None:
9899
r"""
@@ -113,7 +114,7 @@ def blockmean(
113114
114115
Parameters
115116
----------
116-
data : str, {table-like}
117+
data
117118
Pass in (x, y, z) or (longitude, latitude, elevation) values by
118119
providing a file name to an ASCII data table, a 2-D
119120
{table-classes}.
@@ -191,12 +192,12 @@ def blockmean(
191192
)
192193
@kwargs_to_strings(I="sequence", R="sequence", i="sequence_comma", o="sequence_comma")
193194
def blockmedian(
194-
data=None,
195+
data: PathLike | TableLike | None = None,
195196
x=None,
196197
y=None,
197198
z=None,
198199
output_type: Literal["pandas", "numpy", "file"] = "pandas",
199-
outfile: str | None = None,
200+
outfile: PathLike | None = None,
200201
**kwargs,
201202
) -> pd.DataFrame | np.ndarray | None:
202203
r"""
@@ -217,7 +218,7 @@ def blockmedian(
217218
218219
Parameters
219220
----------
220-
data : str, {table-like}
221+
data
221222
Pass in (x, y, z) or (longitude, latitude, elevation) values by
222223
providing a file name to an ASCII data table, a 2-D
223224
{table-classes}.
@@ -289,12 +290,12 @@ def blockmedian(
289290
)
290291
@kwargs_to_strings(I="sequence", R="sequence", i="sequence_comma", o="sequence_comma")
291292
def blockmode(
292-
data=None,
293+
data: PathLike | TableLike | None = None,
293294
x=None,
294295
y=None,
295296
z=None,
296297
output_type: Literal["pandas", "numpy", "file"] = "pandas",
297-
outfile: str | None = None,
298+
outfile: PathLike | None = None,
298299
**kwargs,
299300
) -> pd.DataFrame | np.ndarray | None:
300301
r"""
@@ -315,7 +316,7 @@ def blockmode(
315316
316317
Parameters
317318
----------
318-
data : str, {table-like}
319+
data
319320
Pass in (x, y, z) or (longitude, latitude, elevation) values by
320321
providing a file name to an ASCII data table, a 2-D
321322
{table-classes}.

pygmt/src/contour.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
contour - Contour table data by direct triangulation.
33
"""
44

5+
from pygmt._typing import PathLike, TableLike
56
from pygmt.clib import Session
67
from pygmt.helpers import (
78
build_arg_list,
@@ -37,7 +38,9 @@
3738
t="transparency",
3839
)
3940
@kwargs_to_strings(R="sequence", c="sequence_comma", i="sequence_comma", p="sequence")
40-
def contour(self, data=None, x=None, y=None, z=None, **kwargs):
41+
def contour(
42+
self, data: PathLike | TableLike | None = None, x=None, y=None, z=None, **kwargs
43+
):
4144
r"""
4245
Contour table data by direct triangulation.
4346
@@ -52,7 +55,7 @@ def contour(self, data=None, x=None, y=None, z=None, **kwargs):
5255
5356
Parameters
5457
----------
55-
data : str, {table-like}
58+
data
5659
Pass in (x, y, z) or (longitude, latitude, elevation) values by
5760
providing a file name to an ASCII data table, a 2-D
5861
{table-classes}.

pygmt/src/dimfilter.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44

55
import xarray as xr
6+
from pygmt._typing import PathLike
67
from pygmt.clib import Session
78
from pygmt.exceptions import GMTInvalidInput
89
from pygmt.helpers import build_arg_list, fmt_docstring, kwargs_to_strings, use_alias
@@ -20,7 +21,9 @@
2021
V="verbose",
2122
)
2223
@kwargs_to_strings(I="sequence", R="sequence")
23-
def dimfilter(grid, outgrid: str | None = None, **kwargs) -> xr.DataArray | None:
24+
def dimfilter(
25+
grid: PathLike | xr.DataArray, outgrid: PathLike | None = None, **kwargs
26+
) -> xr.DataArray | None:
2427
r"""
2528
Directional filtering of grids in the space domain.
2629

0 commit comments

Comments
 (0)