Source code for scitex_etc._search

#!/usr/bin/env python3
# File: src/scitex_etc/_search.py

"""Regex pattern search over collections of strings.

Generic cross-cutting helper. Stdlib-only at runtime: numpy, pandas, xarray and
natsort are all *optional* — when present, their array/series types are accepted
as inputs and natural sort ordering is used; otherwise plain lists and the
builtin ``sorted`` are used.
"""

from __future__ import annotations

import re
from collections import abc

try:  # optional — natural sort ordering when available
    from natsort import natsorted as _natsorted
except ImportError:  # pragma: no cover — fallback path

    def _natsorted(iterable):
        return sorted(iterable)


def _to_list(string_or_pattern):
    """Coerce assorted string containers into a plain list of strings."""
    # numpy arrays (optional dependency)
    try:
        import numpy as _np

        if isinstance(string_or_pattern, _np.ndarray):
            return string_or_pattern.tolist()
    except ImportError:
        pass

    # pandas Series / Index (optional dependency)
    try:
        import pandas as _pd

        if isinstance(string_or_pattern, (_pd.Series, _pd.Index)):
            return string_or_pattern.tolist()
    except ImportError:
        pass

    # xarray DataArray (optional, lazy to avoid atexit hang issues)
    try:
        import xarray as _xr

        if isinstance(string_or_pattern, _xr.DataArray):
            return string_or_pattern.tolist()
    except ImportError:
        pass

    if isinstance(string_or_pattern, abc.KeysView):
        return list(string_or_pattern)
    if not isinstance(string_or_pattern, (list, tuple)):
        return [string_or_pattern]
    return string_or_pattern






# EOF