mixins.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. """
  2. Mixin classes for custom array types that don't inherit from ndarray.
  3. """
  4. from numpy._core import umath as um
  5. __all__ = ['NDArrayOperatorsMixin']
  6. def _disables_array_ufunc(obj):
  7. """True when __array_ufunc__ is set to None."""
  8. try:
  9. return obj.__array_ufunc__ is None
  10. except AttributeError:
  11. return False
  12. def _binary_method(ufunc, name):
  13. """Implement a forward binary method with a ufunc, e.g., __add__."""
  14. def func(self, other):
  15. if _disables_array_ufunc(other):
  16. return NotImplemented
  17. return ufunc(self, other)
  18. func.__name__ = f'__{name}__'
  19. return func
  20. def _reflected_binary_method(ufunc, name):
  21. """Implement a reflected binary method with a ufunc, e.g., __radd__."""
  22. def func(self, other):
  23. if _disables_array_ufunc(other):
  24. return NotImplemented
  25. return ufunc(other, self)
  26. func.__name__ = f'__r{name}__'
  27. return func
  28. def _inplace_binary_method(ufunc, name):
  29. """Implement an in-place binary method with a ufunc, e.g., __iadd__."""
  30. def func(self, other):
  31. return ufunc(self, other, out=(self,))
  32. func.__name__ = f'__i{name}__'
  33. return func
  34. def _numeric_methods(ufunc, name):
  35. """Implement forward, reflected and inplace binary methods with a ufunc."""
  36. return (_binary_method(ufunc, name),
  37. _reflected_binary_method(ufunc, name),
  38. _inplace_binary_method(ufunc, name))
  39. def _unary_method(ufunc, name):
  40. """Implement a unary special method with a ufunc."""
  41. def func(self):
  42. return ufunc(self)
  43. func.__name__ = f'__{name}__'
  44. return func
  45. class NDArrayOperatorsMixin:
  46. """Mixin defining all operator special methods using __array_ufunc__.
  47. This class implements the special methods for almost all of Python's
  48. builtin operators defined in the `operator` module, including comparisons
  49. (``==``, ``>``, etc.) and arithmetic (``+``, ``*``, ``-``, etc.), by
  50. deferring to the ``__array_ufunc__`` method, which subclasses must
  51. implement.
  52. It is useful for writing classes that do not inherit from `numpy.ndarray`,
  53. but that should support arithmetic and numpy universal functions like
  54. arrays as described in :external+neps:doc:`nep-0013-ufunc-overrides`.
  55. As a trivial example, consider this implementation of an ``ArrayLike``
  56. class that simply wraps a NumPy array and ensures that the result of any
  57. arithmetic operation is also an ``ArrayLike`` object:
  58. >>> import numbers
  59. >>> class ArrayLike(np.lib.mixins.NDArrayOperatorsMixin):
  60. ... def __init__(self, value):
  61. ... self.value = np.asarray(value)
  62. ...
  63. ... # One might also consider adding the built-in list type to this
  64. ... # list, to support operations like np.add(array_like, list)
  65. ... _HANDLED_TYPES = (np.ndarray, numbers.Number)
  66. ...
  67. ... def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  68. ... out = kwargs.get('out', ())
  69. ... for x in inputs + out:
  70. ... # Only support operations with instances of
  71. ... # _HANDLED_TYPES. Use ArrayLike instead of type(self)
  72. ... # for isinstance to allow subclasses that don't
  73. ... # override __array_ufunc__ to handle ArrayLike objects.
  74. ... if not isinstance(
  75. ... x, self._HANDLED_TYPES + (ArrayLike,)
  76. ... ):
  77. ... return NotImplemented
  78. ...
  79. ... # Defer to the implementation of the ufunc
  80. ... # on unwrapped values.
  81. ... inputs = tuple(x.value if isinstance(x, ArrayLike) else x
  82. ... for x in inputs)
  83. ... if out:
  84. ... kwargs['out'] = tuple(
  85. ... x.value if isinstance(x, ArrayLike) else x
  86. ... for x in out)
  87. ... result = getattr(ufunc, method)(*inputs, **kwargs)
  88. ...
  89. ... if type(result) is tuple:
  90. ... # multiple return values
  91. ... return tuple(type(self)(x) for x in result)
  92. ... elif method == 'at':
  93. ... # no return value
  94. ... return None
  95. ... else:
  96. ... # one return value
  97. ... return type(self)(result)
  98. ...
  99. ... def __repr__(self):
  100. ... return '%s(%r)' % (type(self).__name__, self.value)
  101. In interactions between ``ArrayLike`` objects and numbers or numpy arrays,
  102. the result is always another ``ArrayLike``:
  103. >>> x = ArrayLike([1, 2, 3])
  104. >>> x - 1
  105. ArrayLike(array([0, 1, 2]))
  106. >>> 1 - x
  107. ArrayLike(array([ 0, -1, -2]))
  108. >>> np.arange(3) - x
  109. ArrayLike(array([-1, -1, -1]))
  110. >>> x - np.arange(3)
  111. ArrayLike(array([1, 1, 1]))
  112. Note that unlike ``numpy.ndarray``, ``ArrayLike`` does not allow operations
  113. with arbitrary, unrecognized types. This ensures that interactions with
  114. ArrayLike preserve a well-defined casting hierarchy.
  115. """
  116. __slots__ = ()
  117. # Like np.ndarray, this mixin class implements "Option 1" from the ufunc
  118. # overrides NEP.
  119. # comparisons don't have reflected and in-place versions
  120. __lt__ = _binary_method(um.less, 'lt')
  121. __le__ = _binary_method(um.less_equal, 'le')
  122. __eq__ = _binary_method(um.equal, 'eq')
  123. __ne__ = _binary_method(um.not_equal, 'ne')
  124. __gt__ = _binary_method(um.greater, 'gt')
  125. __ge__ = _binary_method(um.greater_equal, 'ge')
  126. # numeric methods
  127. __add__, __radd__, __iadd__ = _numeric_methods(um.add, 'add')
  128. __sub__, __rsub__, __isub__ = _numeric_methods(um.subtract, 'sub')
  129. __mul__, __rmul__, __imul__ = _numeric_methods(um.multiply, 'mul')
  130. __matmul__, __rmatmul__, __imatmul__ = _numeric_methods(
  131. um.matmul, 'matmul')
  132. __truediv__, __rtruediv__, __itruediv__ = _numeric_methods(
  133. um.true_divide, 'truediv')
  134. __floordiv__, __rfloordiv__, __ifloordiv__ = _numeric_methods(
  135. um.floor_divide, 'floordiv')
  136. __mod__, __rmod__, __imod__ = _numeric_methods(um.remainder, 'mod')
  137. __divmod__ = _binary_method(um.divmod, 'divmod')
  138. __rdivmod__ = _reflected_binary_method(um.divmod, 'divmod')
  139. # __idivmod__ does not exist
  140. # TODO: handle the optional third argument for __pow__?
  141. __pow__, __rpow__, __ipow__ = _numeric_methods(um.power, 'pow')
  142. __lshift__, __rlshift__, __ilshift__ = _numeric_methods(
  143. um.left_shift, 'lshift')
  144. __rshift__, __rrshift__, __irshift__ = _numeric_methods(
  145. um.right_shift, 'rshift')
  146. __and__, __rand__, __iand__ = _numeric_methods(um.bitwise_and, 'and')
  147. __xor__, __rxor__, __ixor__ = _numeric_methods(um.bitwise_xor, 'xor')
  148. __or__, __ror__, __ior__ = _numeric_methods(um.bitwise_or, 'or')
  149. # unary methods
  150. __neg__ = _unary_method(um.negative, 'neg')
  151. __pos__ = _unary_method(um.positive, 'pos')
  152. __abs__ = _unary_method(um.absolute, 'abs')
  153. __invert__ = _unary_method(um.invert, 'invert')