Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/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

61 statements  

1""" 

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

3""" 

4from numpy._core import umath as um 

5 

6__all__ = ['NDArrayOperatorsMixin'] 

7 

8 

9def _disables_array_ufunc(obj): 

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

11 try: 

12 return obj.__array_ufunc__ is None 

13 except AttributeError: 

14 return False 

15 

16 

17def _binary_method(ufunc, name): 

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

19 def func(self, other): 

20 if _disables_array_ufunc(other): 

21 return NotImplemented 

22 return ufunc(self, other) 

23 func.__name__ = f'__{name}__' 

24 return func 

25 

26 

27def _reflected_binary_method(ufunc, name): 

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

29 def func(self, other): 

30 if _disables_array_ufunc(other): 

31 return NotImplemented 

32 return ufunc(other, self) 

33 func.__name__ = f'__r{name}__' 

34 return func 

35 

36 

37def _inplace_binary_method(ufunc, name): 

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

39 def func(self, other): 

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

41 func.__name__ = f'__i{name}__' 

42 return func 

43 

44 

45def _numeric_methods(ufunc, name): 

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

47 return (_binary_method(ufunc, name), 

48 _reflected_binary_method(ufunc, name), 

49 _inplace_binary_method(ufunc, name)) 

50 

51 

52def _unary_method(ufunc, name): 

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

54 def func(self): 

55 return ufunc(self) 

56 func.__name__ = f'__{name}__' 

57 return func 

58 

59 

60class NDArrayOperatorsMixin: 

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

62 

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

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

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

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

67 implement. 

68 

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

70 but that should support arithmetic and numpy universal functions like 

71 arrays as described in :external+neps:doc:`nep-0013-ufunc-overrides`. 

72 

73 As a trivial example, consider this implementation of an ``ArrayLike`` 

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

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

76 

77 >>> import numbers 

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

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

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

81 ... 

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

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

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

85 ... 

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

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

88 ... for x in inputs + out: 

89 ... # Only support operations with instances of 

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

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

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

93 ... if not isinstance( 

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

95 ... ): 

96 ... return NotImplemented 

97 ... 

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

99 ... # on unwrapped values. 

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

101 ... for x in inputs) 

102 ... if out: 

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

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

105 ... for x in out) 

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

107 ... 

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

109 ... # multiple return values 

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

111 ... elif method == 'at': 

112 ... # no return value 

113 ... return None 

114 ... else: 

115 ... # one return value 

116 ... return type(self)(result) 

117 ... 

118 ... def __repr__(self): 

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

120 

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

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

123 

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

125 >>> x - 1 

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

127 >>> 1 - x 

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

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

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

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

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

133 

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

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

136 ArrayLike preserve a well-defined casting hierarchy. 

137 

138 """ 

139 

140 __slots__ = () 

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

142 # overrides NEP. 

143 

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

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

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

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

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

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

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

151 

152 # numeric methods 

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

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

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

156 __matmul__, __rmatmul__, __imatmul__ = _numeric_methods( 

157 um.matmul, 'matmul') 

158 __truediv__, __rtruediv__, __itruediv__ = _numeric_methods( 

159 um.true_divide, 'truediv') 

160 __floordiv__, __rfloordiv__, __ifloordiv__ = _numeric_methods( 

161 um.floor_divide, 'floordiv') 

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

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

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

165 # __idivmod__ does not exist 

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

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

168 __lshift__, __rlshift__, __ilshift__ = _numeric_methods( 

169 um.left_shift, 'lshift') 

170 __rshift__, __rrshift__, __irshift__ = _numeric_methods( 

171 um.right_shift, 'rshift') 

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

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

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

175 

176 # unary methods 

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

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

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

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