Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/numpy/exceptions.py: 54%
35 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-09 06:12 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-09 06:12 +0000
1"""
2Exceptions and Warnings (:mod:`numpy.exceptions`)
3=================================================
5General exceptions used by NumPy. Note that some exceptions may be module
6specific, such as linear algebra errors.
8.. versionadded:: NumPy 1.25
10 The exceptions module is new in NumPy 1.25. Older exceptions remain
11 available through the main NumPy namespace for compatibility.
13.. currentmodule:: numpy.exceptions
15Warnings
16--------
17.. autosummary::
18 :toctree: generated/
20 ComplexWarning Given when converting complex to real.
21 VisibleDeprecationWarning Same as a DeprecationWarning, but more visible.
22 RankWarning Issued when the design matrix is rank deficient.
24Exceptions
25----------
26.. autosummary::
27 :toctree: generated/
29 AxisError Given when an axis was invalid.
30 DTypePromotionError Given when no common dtype could be found.
31 TooHardError Error specific to `numpy.shares_memory`.
33"""
36__all__ = [
37 "ComplexWarning", "VisibleDeprecationWarning", "ModuleDeprecationWarning",
38 "TooHardError", "AxisError", "DTypePromotionError"]
41# Disallow reloading this module so as to preserve the identities of the
42# classes defined here.
43if '_is_loaded' in globals():
44 raise RuntimeError('Reloading numpy._globals is not allowed')
45_is_loaded = True
48class ComplexWarning(RuntimeWarning):
49 """
50 The warning raised when casting a complex dtype to a real dtype.
52 As implemented, casting a complex number to a real discards its imaginary
53 part, but this behavior may not be what the user actually wants.
55 """
56 pass
59class ModuleDeprecationWarning(DeprecationWarning):
60 """Module deprecation warning.
62 .. warning::
64 This warning should not be used, since nose testing is not relevant
65 anymore.
67 The nose tester turns ordinary Deprecation warnings into test failures.
68 That makes it hard to deprecate whole modules, because they get
69 imported by default. So this is a special Deprecation warning that the
70 nose tester will let pass without making tests fail.
72 """
73 pass
76class VisibleDeprecationWarning(UserWarning):
77 """Visible deprecation warning.
79 By default, python will not show deprecation warnings, so this class
80 can be used when a very visible warning is helpful, for example because
81 the usage is most likely a user bug.
83 """
84 pass
87class RankWarning(RuntimeWarning):
88 """Matrix rank warning.
90 Issued by polynomial functions when the design matrix is rank deficient.
92 """
93 pass
96# Exception used in shares_memory()
97class TooHardError(RuntimeError):
98 """max_work was exceeded.
100 This is raised whenever the maximum number of candidate solutions
101 to consider specified by the ``max_work`` parameter is exceeded.
102 Assigning a finite number to max_work may have caused the operation
103 to fail.
105 """
106 pass
109class AxisError(ValueError, IndexError):
110 """Axis supplied was invalid.
112 This is raised whenever an ``axis`` parameter is specified that is larger
113 than the number of array dimensions.
114 For compatibility with code written against older numpy versions, which
115 raised a mixture of :exc:`ValueError` and :exc:`IndexError` for this
116 situation, this exception subclasses both to ensure that
117 ``except ValueError`` and ``except IndexError`` statements continue
118 to catch ``AxisError``.
120 .. versionadded:: 1.13
122 Parameters
123 ----------
124 axis : int or str
125 The out of bounds axis or a custom exception message.
126 If an axis is provided, then `ndim` should be specified as well.
127 ndim : int, optional
128 The number of array dimensions.
129 msg_prefix : str, optional
130 A prefix for the exception message.
132 Attributes
133 ----------
134 axis : int, optional
135 The out of bounds axis or ``None`` if a custom exception
136 message was provided. This should be the axis as passed by
137 the user, before any normalization to resolve negative indices.
139 .. versionadded:: 1.22
140 ndim : int, optional
141 The number of array dimensions or ``None`` if a custom exception
142 message was provided.
144 .. versionadded:: 1.22
147 Examples
148 --------
149 >>> array_1d = np.arange(10)
150 >>> np.cumsum(array_1d, axis=1)
151 Traceback (most recent call last):
152 ...
153 numpy.exceptions.AxisError: axis 1 is out of bounds for array of dimension 1
155 Negative axes are preserved:
157 >>> np.cumsum(array_1d, axis=-2)
158 Traceback (most recent call last):
159 ...
160 numpy.exceptions.AxisError: axis -2 is out of bounds for array of dimension 1
162 The class constructor generally takes the axis and arrays'
163 dimensionality as arguments:
165 >>> print(np.exceptions.AxisError(2, 1, msg_prefix='error'))
166 error: axis 2 is out of bounds for array of dimension 1
168 Alternatively, a custom exception message can be passed:
170 >>> print(np.exceptions.AxisError('Custom error message'))
171 Custom error message
173 """
175 __slots__ = ("axis", "ndim", "_msg")
177 def __init__(self, axis, ndim=None, msg_prefix=None):
178 if ndim is msg_prefix is None:
179 # single-argument form: directly set the error message
180 self._msg = axis
181 self.axis = None
182 self.ndim = None
183 else:
184 self._msg = msg_prefix
185 self.axis = axis
186 self.ndim = ndim
188 def __str__(self):
189 axis = self.axis
190 ndim = self.ndim
192 if axis is ndim is None:
193 return self._msg
194 else:
195 msg = f"axis {axis} is out of bounds for array of dimension {ndim}"
196 if self._msg is not None:
197 msg = f"{self._msg}: {msg}"
198 return msg
201class DTypePromotionError(TypeError):
202 """Multiple DTypes could not be converted to a common one.
204 This exception derives from ``TypeError`` and is raised whenever dtypes
205 cannot be converted to a single common one. This can be because they
206 are of a different category/class or incompatible instances of the same
207 one (see Examples).
209 Notes
210 -----
211 Many functions will use promotion to find the correct result and
212 implementation. For these functions the error will typically be chained
213 with a more specific error indicating that no implementation was found
214 for the input dtypes.
216 Typically promotion should be considered "invalid" between the dtypes of
217 two arrays when `arr1 == arr2` can safely return all ``False`` because the
218 dtypes are fundamentally different.
220 Examples
221 --------
222 Datetimes and complex numbers are incompatible classes and cannot be
223 promoted:
225 >>> np.result_type(np.dtype("M8[s]"), np.complex128)
226 DTypePromotionError: The DType <class 'numpy.dtype[datetime64]'> could not
227 be promoted by <class 'numpy.dtype[complex128]'>. This means that no common
228 DType exists for the given inputs. For example they cannot be stored in a
229 single array unless the dtype is `object`. The full list of DTypes is:
230 (<class 'numpy.dtype[datetime64]'>, <class 'numpy.dtype[complex128]'>)
232 For example for structured dtypes, the structure can mismatch and the
233 same ``DTypePromotionError`` is given when two structured dtypes with
234 a mismatch in their number of fields is given:
236 >>> dtype1 = np.dtype([("field1", np.float64), ("field2", np.int64)])
237 >>> dtype2 = np.dtype([("field1", np.float64)])
238 >>> np.promote_types(dtype1, dtype2)
239 DTypePromotionError: field names `('field1', 'field2')` and `('field1',)`
240 mismatch.
242 """
243 pass