|
2 | 2 | # defined in xarray |
3 | 3 |
|
4 | 4 |
|
5 | | -from typing import Any |
| 5 | +from typing import Any, Iterable |
6 | 6 |
|
| 7 | +import dask.array |
7 | 8 | import numpy as np |
| 9 | +import pandas as pd |
8 | 10 |
|
9 | 11 |
|
10 | 12 | def is_duck_array(value: Any) -> bool: |
@@ -32,3 +34,47 @@ def is_dask_collection(x): |
32 | 34 |
|
33 | 35 | def is_duck_dask_array(x): |
34 | 36 | return is_duck_array(x) and is_dask_collection(x) |
| 37 | + |
| 38 | + |
| 39 | +class ReprObject: |
| 40 | + """Object that prints as the given value, for use with sentinel values.""" |
| 41 | + |
| 42 | + __slots__ = ("_value",) |
| 43 | + |
| 44 | + def __init__(self, value: str): |
| 45 | + self._value = value |
| 46 | + |
| 47 | + def __repr__(self) -> str: |
| 48 | + return self._value |
| 49 | + |
| 50 | + def __eq__(self, other) -> bool: |
| 51 | + if isinstance(other, ReprObject): |
| 52 | + return self._value == other._value |
| 53 | + return False |
| 54 | + |
| 55 | + def __hash__(self) -> int: |
| 56 | + return hash((type(self), self._value)) |
| 57 | + |
| 58 | + def __dask_tokenize__(self): |
| 59 | + from dask.base import normalize_token |
| 60 | + |
| 61 | + return normalize_token((type(self), self._value)) |
| 62 | + |
| 63 | + |
| 64 | +def is_scalar(value: Any, include_0d: bool = True) -> bool: |
| 65 | + """Whether to treat a value as a scalar. |
| 66 | +
|
| 67 | + Any non-iterable, string, or 0-D array |
| 68 | + """ |
| 69 | + NON_NUMPY_SUPPORTED_ARRAY_TYPES = (dask.array.Array, pd.Index) |
| 70 | + |
| 71 | + if include_0d: |
| 72 | + include_0d = getattr(value, "ndim", None) == 0 |
| 73 | + return ( |
| 74 | + include_0d |
| 75 | + or isinstance(value, (str, bytes)) |
| 76 | + or not ( |
| 77 | + isinstance(value, (Iterable,) + NON_NUMPY_SUPPORTED_ARRAY_TYPES) |
| 78 | + or hasattr(value, "__array_function__") |
| 79 | + ) |
| 80 | + ) |
0 commit comments