Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/numpy/exceptions.py: 48%

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

31 statements  

1""" 

2Exceptions and Warnings (:mod:`numpy.exceptions`) 

3================================================= 

4 

5General exceptions used by NumPy. Note that some exceptions may be module 

6specific, such as linear algebra errors. 

7 

8.. versionadded:: NumPy 1.25 

9 

10 The exceptions module is new in NumPy 1.25. Older exceptions remain 

11 available through the main NumPy namespace for compatibility. 

12 

13.. currentmodule:: numpy.exceptions 

14 

15Warnings 

16-------- 

17.. autosummary:: 

18 :toctree: generated/ 

19 

20 ComplexWarning Given when converting complex to real. 

21 VisibleDeprecationWarning Same as a DeprecationWarning, but more visible. 

22 

23Exceptions 

24---------- 

25.. autosummary:: 

26 :toctree: generated/ 

27 

28 AxisError Given when an axis was invalid. 

29 DTypePromotionError Given when no common dtype could be found. 

30 TooHardError Error specific to `numpy.shares_memory`. 

31 

32""" 

33 

34 

35__all__ = [ 

36 "ComplexWarning", "VisibleDeprecationWarning", "ModuleDeprecationWarning", 

37 "TooHardError", "AxisError", "DTypePromotionError"] 

38 

39 

40# Disallow reloading this module so as to preserve the identities of the 

41# classes defined here. 

42if '_is_loaded' in globals(): 

43 raise RuntimeError('Reloading numpy._globals is not allowed') 

44_is_loaded = True 

45 

46 

47class ComplexWarning(RuntimeWarning): 

48 """ 

49 The warning raised when casting a complex dtype to a real dtype. 

50 

51 As implemented, casting a complex number to a real discards its imaginary 

52 part, but this behavior may not be what the user actually wants. 

53 

54 """ 

55 pass 

56 

57 

58class ModuleDeprecationWarning(DeprecationWarning): 

59 """Module deprecation warning. 

60 

61 .. warning:: 

62 

63 This warning should not be used, since nose testing is not relevant 

64 anymore. 

65 

66 The nose tester turns ordinary Deprecation warnings into test failures. 

67 That makes it hard to deprecate whole modules, because they get 

68 imported by default. So this is a special Deprecation warning that the 

69 nose tester will let pass without making tests fail. 

70 

71 """ 

72 

73 

74class VisibleDeprecationWarning(UserWarning): 

75 """Visible deprecation warning. 

76 

77 By default, python will not show deprecation warnings, so this class 

78 can be used when a very visible warning is helpful, for example because 

79 the usage is most likely a user bug. 

80 

81 """ 

82 

83 

84# Exception used in shares_memory() 

85class TooHardError(RuntimeError): 

86 """max_work was exceeded. 

87 

88 This is raised whenever the maximum number of candidate solutions 

89 to consider specified by the ``max_work`` parameter is exceeded. 

90 Assigning a finite number to max_work may have caused the operation 

91 to fail. 

92 

93 """ 

94 

95 pass 

96 

97 

98class AxisError(ValueError, IndexError): 

99 """Axis supplied was invalid. 

100 

101 This is raised whenever an ``axis`` parameter is specified that is larger 

102 than the number of array dimensions. 

103 For compatibility with code written against older numpy versions, which 

104 raised a mixture of `ValueError` and `IndexError` for this situation, this 

105 exception subclasses both to ensure that ``except ValueError`` and 

106 ``except IndexError`` statements continue to catch `AxisError`. 

107 

108 .. versionadded:: 1.13 

109 

110 Parameters 

111 ---------- 

112 axis : int or str 

113 The out of bounds axis or a custom exception message. 

114 If an axis is provided, then `ndim` should be specified as well. 

115 ndim : int, optional 

116 The number of array dimensions. 

117 msg_prefix : str, optional 

118 A prefix for the exception message. 

119 

120 Attributes 

121 ---------- 

122 axis : int, optional 

123 The out of bounds axis or ``None`` if a custom exception 

124 message was provided. This should be the axis as passed by 

125 the user, before any normalization to resolve negative indices. 

126 

127 .. versionadded:: 1.22 

128 ndim : int, optional 

129 The number of array dimensions or ``None`` if a custom exception 

130 message was provided. 

131 

132 .. versionadded:: 1.22 

133 

134 

135 Examples 

136 -------- 

137 >>> array_1d = np.arange(10) 

138 >>> np.cumsum(array_1d, axis=1) 

139 Traceback (most recent call last): 

140 ... 

141 numpy.exceptions.AxisError: axis 1 is out of bounds for array of dimension 1 

142 

143 Negative axes are preserved: 

144 

145 >>> np.cumsum(array_1d, axis=-2) 

146 Traceback (most recent call last): 

147 ... 

148 numpy.exceptions.AxisError: axis -2 is out of bounds for array of dimension 1 

149 

150 The class constructor generally takes the axis and arrays' 

151 dimensionality as arguments: 

152 

153 >>> print(np.AxisError(2, 1, msg_prefix='error')) 

154 error: axis 2 is out of bounds for array of dimension 1 

155 

156 Alternatively, a custom exception message can be passed: 

157 

158 >>> print(np.AxisError('Custom error message')) 

159 Custom error message 

160 

161 """ 

162 

163 __slots__ = ("axis", "ndim", "_msg") 

164 

165 def __init__(self, axis, ndim=None, msg_prefix=None): 

166 if ndim is msg_prefix is None: 

167 # single-argument form: directly set the error message 

168 self._msg = axis 

169 self.axis = None 

170 self.ndim = None 

171 else: 

172 self._msg = msg_prefix 

173 self.axis = axis 

174 self.ndim = ndim 

175 

176 def __str__(self): 

177 axis = self.axis 

178 ndim = self.ndim 

179 

180 if axis is ndim is None: 

181 return self._msg 

182 else: 

183 msg = f"axis {axis} is out of bounds for array of dimension {ndim}" 

184 if self._msg is not None: 

185 msg = f"{self._msg}: {msg}" 

186 return msg 

187 

188 

189class DTypePromotionError(TypeError): 

190 """Multiple DTypes could not be converted to a common one. 

191 

192 This exception derives from ``TypeError`` and is raised whenever dtypes 

193 cannot be converted to a single common one. This can be because they 

194 are of a different category/class or incompatible instances of the same 

195 one (see Examples). 

196 

197 Notes 

198 ----- 

199 Many functions will use promotion to find the correct result and 

200 implementation. For these functions the error will typically be chained 

201 with a more specific error indicating that no implementation was found 

202 for the input dtypes. 

203 

204 Typically promotion should be considered "invalid" between the dtypes of 

205 two arrays when `arr1 == arr2` can safely return all ``False`` because the 

206 dtypes are fundamentally different. 

207 

208 Examples 

209 -------- 

210 Datetimes and complex numbers are incompatible classes and cannot be 

211 promoted: 

212 

213 >>> np.result_type(np.dtype("M8[s]"), np.complex128) 

214 DTypePromotionError: The DType <class 'numpy.dtype[datetime64]'> could not 

215 be promoted by <class 'numpy.dtype[complex128]'>. This means that no common 

216 DType exists for the given inputs. For example they cannot be stored in a 

217 single array unless the dtype is `object`. The full list of DTypes is: 

218 (<class 'numpy.dtype[datetime64]'>, <class 'numpy.dtype[complex128]'>) 

219 

220 For example for structured dtypes, the structure can mismatch and the 

221 same ``DTypePromotionError`` is given when two structured dtypes with 

222 a mismatch in their number of fields is given: 

223 

224 >>> dtype1 = np.dtype([("field1", np.float64), ("field2", np.int64)]) 

225 >>> dtype2 = np.dtype([("field1", np.float64)]) 

226 >>> np.promote_types(dtype1, dtype2) 

227 DTypePromotionError: field names `('field1', 'field2')` and `('field1',)` 

228 mismatch. 

229 

230 """ 

231 pass