From 17c1e9ca28acbb9f35223b0bb770a8dc8bb75843 Mon Sep 17 00:00:00 2001 From: Wei Ji <23487320+weiji14@users.noreply.github.com> Date: Fri, 11 Oct 2024 19:20:19 +1300 Subject: [PATCH] Move StringArrayTypes to pygmt/_typing.py Also improve docstring of strings_to_ctypes_array function to mention np.ndarray as supported input. --- pygmt/_typing.py | 10 ++++++++++ pygmt/clib/conversion.py | 16 ++++------------ pygmt/clib/session.py | 11 +---------- 3 files changed, 15 insertions(+), 22 deletions(-) diff --git a/pygmt/_typing.py b/pygmt/_typing.py index bbc7d596c65..4a57c3c7678 100644 --- a/pygmt/_typing.py +++ b/pygmt/_typing.py @@ -2,7 +2,17 @@ Type aliases for type hints. """ +import contextlib +import importlib +from collections.abc import Sequence from typing import Literal +import numpy as np + # Anchor codes AnchorCode = Literal["TL", "TC", "TR", "ML", "MC", "MR", "BL", "BC", "BR"] + +# String array types +StringArrayTypes = Sequence[str] | np.ndarray +with contextlib.suppress(ImportError): + StringArrayTypes |= importlib.import_module(name="pyarrow").StringArray diff --git a/pygmt/clib/conversion.py b/pygmt/clib/conversion.py index f4c8bb50fd2..5a3f708af1a 100644 --- a/pygmt/clib/conversion.py +++ b/pygmt/clib/conversion.py @@ -9,17 +9,9 @@ import numpy as np import pandas as pd from packaging.version import Version +from pygmt._typing import StringArrayTypes from pygmt.exceptions import GMTInvalidInput -StringArrayTypes = Sequence[str] | np.ndarray - -try: - import pyarrow as pa - - StringArrayTypes |= pa.StringArray -except ImportError: - pa = None - def dataarray_to_matrix(grid): """ @@ -292,13 +284,13 @@ def sequence_to_ctypes_array( def strings_to_ctypes_array(strings: StringArrayTypes) -> ctp.Array: """ - Convert a sequence (e.g., a list) of strings or a pyarrow.StringArray into a ctypes - array. + Convert a sequence (e.g., a list) or numpy.ndarray of strings or a + pyarrow.StringArray into a ctypes array. Parameters ---------- strings - A sequence of strings or a pyarrow.StringArray. + A sequence of strings, a numpy.ndarray of str dtype, or a pyarrow.StringArray. Returns ------- diff --git a/pygmt/clib/session.py b/pygmt/clib/session.py index af5678aef09..f53a5af2cf5 100644 --- a/pygmt/clib/session.py +++ b/pygmt/clib/session.py @@ -17,6 +17,7 @@ import numpy as np import pandas as pd import xarray as xr +from pygmt._typing import StringArrayTypes from pygmt.clib.conversion import ( array_to_datetime, dataarray_to_matrix, @@ -34,16 +35,6 @@ tempfile_from_image, ) -StringArrayTypes = Sequence[str] | np.ndarray - -try: - import pyarrow as pa - - StringArrayTypes |= pa.StringArray -except ImportError: - pa = None - - FAMILIES = [ "GMT_IS_DATASET", # Entity is a data table "GMT_IS_GRID", # Entity is a grid