Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.10/site-packages/numpy/lib/mixins.py: 80%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

60 statements  

1""" 

2Mixin classes for custom array types that don't inherit from ndarray. 

3""" 

4from numpy._core import umath as um 

5 

6 

7__all__ = ['NDArrayOperatorsMixin'] 

8 

9 

10def _disables_array_ufunc(obj): 

11 """True when __array_ufunc__ is set to None.""" 

12 try: 

13 return obj.__array_ufunc__ is None 

14 except AttributeError: 

15 return False 

16 

17 

18def _binary_method(ufunc, name): 

19 """Implement a forward binary method with a ufunc, e.g., __add__.""" 

20 def func(self, other): 

21 if _disables_array_ufunc(other): 

22 return NotImplemented 

23 return ufunc(self, other) 

24 func.__name__ = '__{}__'.format(name) 

25 return func 

26 

27 

28def _reflected_binary_method(ufunc, name): 

29 """Implement a reflected binary method with a ufunc, e.g., __radd__.""" 

30 def func(self, other): 

31 if _disables_array_ufunc(other): 

32 return NotImplemented 

33 return ufunc(other, self) 

34 func.__name__ = '__r{}__'.format(name) 

35 return func 

36 

37 

38def _inplace_binary_method(ufunc, name): 

39 """Implement an in-place binary method with a ufunc, e.g., __iadd__.""" 

40 def func(self, other): 

41 return ufunc(self, other, out=(self,)) 

42 func.__name__ = '__i{}__'.format(name) 

43 return func 

44 

45 

46def _numeric_methods(ufunc, name): 

47 """Implement forward, reflected and inplace binary methods with a ufunc.""" 

48 return (_binary_method(ufunc, name), 

49 _reflected_binary_method(ufunc, name), 

50 _inplace_binary_method(ufunc, name)) 

51 

52 

53def _unary_method(ufunc, name): 

54 """Implement a unary special method with a ufunc.""" 

55 def func(self): 

56 return ufunc(self) 

57 func.__name__ = '__{}__'.format(name) 

58 return func 

59 

60 

61class NDArrayOperatorsMixin: 

62 """Mixin defining all operator special methods using __array_ufunc__. 

63 

64 This class implements the special methods for almost all of Python's 

65 builtin operators defined in the `operator` module, including comparisons 

66 (``==``, ``>``, etc.) and arithmetic (``+``, ``*``, ``-``, etc.), by 

67 deferring to the ``__array_ufunc__`` method, which subclasses must 

68 implement. 

69 

70 It is useful for writing classes that do not inherit from `numpy.ndarray`, 

71 but that should support arithmetic and numpy universal functions like 

72 arrays as described in `A Mechanism for Overriding Ufuncs 

73 <https://numpy.org/neps/nep-0013-ufunc-overrides.html>`_. 

74 

75 As an trivial example, consider this implementation of an ``ArrayLike`` 

76 class that simply wraps a NumPy array and ensures that the result of any 

77 arithmetic operation is also an ``ArrayLike`` object: 

78 

79 >>> import numbers 

80 >>> class ArrayLike(np.lib.mixins.NDArrayOperatorsMixin): 

81 ... def __init__(self, value): 

82 ... self.value = np.asarray(value) 

83 ... 

84 ... # One might also consider adding the built-in list type to this 

85 ... # list, to support operations like np.add(array_like, list) 

86 ... _HANDLED_TYPES = (np.ndarray, numbers.Number) 

87 ... 

88 ... def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): 

89 ... out = kwargs.get('out', ()) 

90 ... for x in inputs + out: 

91 ... # Only support operations with instances of 

92 ... # _HANDLED_TYPES. Use ArrayLike instead of type(self) 

93 ... # for isinstance to allow subclasses that don't 

94 ... # override __array_ufunc__ to handle ArrayLike objects. 

95 ... if not isinstance( 

96 ... x, self._HANDLED_TYPES + (ArrayLike,) 

97 ... ): 

98 ... return NotImplemented 

99 ... 

100 ... # Defer to the implementation of the ufunc 

101 ... # on unwrapped values. 

102 ... inputs = tuple(x.value if isinstance(x, ArrayLike) else x 

103 ... for x in inputs) 

104 ... if out: 

105 ... kwargs['out'] = tuple( 

106 ... x.value if isinstance(x, ArrayLike) else x 

107 ... for x in out) 

108 ... result = getattr(ufunc, method)(*inputs, **kwargs) 

109 ... 

110 ... if type(result) is tuple: 

111 ... # multiple return values 

112 ... return tuple(type(self)(x) for x in result) 

113 ... elif method == 'at': 

114 ... # no return value 

115 ... return None 

116 ... else: 

117 ... # one return value 

118 ... return type(self)(result) 

119 ... 

120 ... def __repr__(self): 

121 ... return '%s(%r)' % (type(self).__name__, self.value) 

122 

123 In interactions between ``ArrayLike`` objects and numbers or numpy arrays, 

124 the result is always another ``ArrayLike``: 

125 

126 >>> x = ArrayLike([1, 2, 3]) 

127 >>> x - 1 

128 ArrayLike(array([0, 1, 2])) 

129 >>> 1 - x 

130 ArrayLike(array([ 0, -1, -2])) 

131 >>> np.arange(3) - x 

132 ArrayLike(array([-1, -1, -1])) 

133 >>> x - np.arange(3) 

134 ArrayLike(array([1, 1, 1])) 

135 

136 Note that unlike ``numpy.ndarray``, ``ArrayLike`` does not allow operations 

137 with arbitrary, unrecognized types. This ensures that interactions with 

138 ArrayLike preserve a well-defined casting hierarchy. 

139 

140 """ 

141 __slots__ = () 

142 # Like np.ndarray, this mixin class implements "Option 1" from the ufunc 

143 # overrides NEP. 

144 

145 # comparisons don't have reflected and in-place versions 

146 __lt__ = _binary_method(um.less, 'lt') 

147 __le__ = _binary_method(um.less_equal, 'le') 

148 __eq__ = _binary_method(um.equal, 'eq') 

149 __ne__ = _binary_method(um.not_equal, 'ne') 

150 __gt__ = _binary_method(um.greater, 'gt') 

151 __ge__ = _binary_method(um.greater_equal, 'ge') 

152 

153 # numeric methods 

154 __add__, __radd__, __iadd__ = _numeric_methods(um.add, 'add') 

155 __sub__, __rsub__, __isub__ = _numeric_methods(um.subtract, 'sub') 

156 __mul__, __rmul__, __imul__ = _numeric_methods(um.multiply, 'mul') 

157 __matmul__, __rmatmul__, __imatmul__ = _numeric_methods( 

158 um.matmul, 'matmul') 

159 # Python 3 does not use __div__, __rdiv__, or __idiv__ 

160 __truediv__, __rtruediv__, __itruediv__ = _numeric_methods( 

161 um.true_divide, 'truediv') 

162 __floordiv__, __rfloordiv__, __ifloordiv__ = _numeric_methods( 

163 um.floor_divide, 'floordiv') 

164 __mod__, __rmod__, __imod__ = _numeric_methods(um.remainder, 'mod') 

165 __divmod__ = _binary_method(um.divmod, 'divmod') 

166 __rdivmod__ = _reflected_binary_method(um.divmod, 'divmod') 

167 # __idivmod__ does not exist 

168 # TODO: handle the optional third argument for __pow__? 

169 __pow__, __rpow__, __ipow__ = _numeric_methods(um.power, 'pow') 

170 __lshift__, __rlshift__, __ilshift__ = _numeric_methods( 

171 um.left_shift, 'lshift') 

172 __rshift__, __rrshift__, __irshift__ = _numeric_methods( 

173 um.right_shift, 'rshift') 

174 __and__, __rand__, __iand__ = _numeric_methods(um.bitwise_and, 'and') 

175 __xor__, __rxor__, __ixor__ = _numeric_methods(um.bitwise_xor, 'xor') 

176 __or__, __ror__, __ior__ = _numeric_methods(um.bitwise_or, 'or') 

177 

178 # unary methods 

179 __neg__ = _unary_method(um.negative, 'neg') 

180 __pos__ = _unary_method(um.positive, 'pos') 

181 __abs__ = _unary_method(um.absolute, 'abs') 

182 __invert__ = _unary_method(um.invert, 'invert')