| 9 | # docstring for NDArrayOperatorsMixin. |
| 10 | |
| 11 | class ArrayLike(np.lib.mixins.NDArrayOperatorsMixin): |
| 12 | def __init__(self, value): |
| 13 | self.value = np.asarray(value) |
| 14 | |
| 15 | # One might also consider adding the built-in list type to this |
| 16 | # list, to support operations like np.add(array_like, list) |
| 17 | _HANDLED_TYPES = (np.ndarray, numbers.Number) |
| 18 | |
| 19 | def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): |
| 20 | out = kwargs.get('out', ()) |
| 21 | for x in inputs + out: |
| 22 | # Only support operations with instances of _HANDLED_TYPES. |
| 23 | # Use ArrayLike instead of type(self) for isinstance to |
| 24 | # allow subclasses that don't override __array_ufunc__ to |
| 25 | # handle ArrayLike objects. |
| 26 | if not isinstance(x, self._HANDLED_TYPES + (ArrayLike,)): |
| 27 | return NotImplemented |
| 28 | |
| 29 | # Defer to the implementation of the ufunc on unwrapped values. |
| 30 | inputs = tuple(x.value if isinstance(x, ArrayLike) else x |
| 31 | for x in inputs) |
| 32 | if out: |
| 33 | kwargs['out'] = tuple( |
| 34 | x.value if isinstance(x, ArrayLike) else x |
| 35 | for x in out) |
| 36 | result = getattr(ufunc, method)(*inputs, **kwargs) |
| 37 | |
| 38 | if type(result) is tuple: |
| 39 | # multiple return values |
| 40 | return tuple(type(self)(x) for x in result) |
| 41 | elif method == 'at': |
| 42 | # no return value |
| 43 | return None |
| 44 | else: |
| 45 | # one return value |
| 46 | return type(self)(result) |
| 47 | |
| 48 | def __repr__(self): |
| 49 | return '%s(%r)' % (type(self).__name__, self.value) |
| 50 | |
| 51 | |
| 52 | def wrap_array_like(result): |
no outgoing calls