Return an ndarray if the given object is implicitly convertible to ndarray, and numpy is already imported, otherwise None.
(obj: object)
| 730 | |
| 731 | |
| 732 | def _as_numpy_array(obj: object) -> Optional["ndarray"]: |
| 733 | """ |
| 734 | Return an ndarray if the given object is implicitly convertible to ndarray, |
| 735 | and numpy is already imported, otherwise None. |
| 736 | """ |
| 737 | import sys |
| 738 | |
| 739 | np: Any = sys.modules.get("numpy") |
| 740 | if np is not None: |
| 741 | # avoid infinite recursion on numpy scalars, which have __array__ |
| 742 | if np.isscalar(obj): |
| 743 | return None |
| 744 | elif isinstance(obj, np.ndarray): |
| 745 | return obj |
| 746 | elif hasattr(obj, "__array__") or hasattr("obj", "__array_interface__"): |
| 747 | return np.asarray(obj) |
| 748 | return None |
| 749 | |
| 750 | |
| 751 | # builtin pytest.raises helper |
no test coverage detected