exceptions.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. """
  2. Exceptions and Warnings
  3. =======================
  4. General exceptions used by NumPy. Note that some exceptions may be module
  5. specific, such as linear algebra errors.
  6. .. versionadded:: NumPy 1.25
  7. The exceptions module is new in NumPy 1.25.
  8. .. currentmodule:: numpy.exceptions
  9. Warnings
  10. --------
  11. .. autosummary::
  12. :toctree: generated/
  13. ComplexWarning Given when converting complex to real.
  14. VisibleDeprecationWarning Same as a DeprecationWarning, but more visible.
  15. RankWarning Issued when the design matrix is rank deficient.
  16. Exceptions
  17. ----------
  18. .. autosummary::
  19. :toctree: generated/
  20. AxisError Given when an axis was invalid.
  21. DTypePromotionError Given when no common dtype could be found.
  22. TooHardError Error specific to `numpy.shares_memory`.
  23. """
  24. __all__ = [
  25. "ComplexWarning", "VisibleDeprecationWarning", "ModuleDeprecationWarning",
  26. "TooHardError", "AxisError", "DTypePromotionError"]
  27. # Disallow reloading this module so as to preserve the identities of the
  28. # classes defined here.
  29. if '_is_loaded' in globals():
  30. raise RuntimeError('Reloading numpy._globals is not allowed')
  31. _is_loaded = True
  32. class ComplexWarning(RuntimeWarning):
  33. """
  34. The warning raised when casting a complex dtype to a real dtype.
  35. As implemented, casting a complex number to a real discards its imaginary
  36. part, but this behavior may not be what the user actually wants.
  37. """
  38. pass
  39. class ModuleDeprecationWarning(DeprecationWarning):
  40. """Module deprecation warning.
  41. .. warning::
  42. This warning should not be used, since nose testing is not relevant
  43. anymore.
  44. The nose tester turns ordinary Deprecation warnings into test failures.
  45. That makes it hard to deprecate whole modules, because they get
  46. imported by default. So this is a special Deprecation warning that the
  47. nose tester will let pass without making tests fail.
  48. """
  49. pass
  50. class VisibleDeprecationWarning(UserWarning):
  51. """Visible deprecation warning.
  52. By default, python will not show deprecation warnings, so this class
  53. can be used when a very visible warning is helpful, for example because
  54. the usage is most likely a user bug.
  55. """
  56. pass
  57. class RankWarning(RuntimeWarning):
  58. """Matrix rank warning.
  59. Issued by polynomial functions when the design matrix is rank deficient.
  60. """
  61. pass
  62. # Exception used in shares_memory()
  63. class TooHardError(RuntimeError):
  64. """``max_work`` was exceeded.
  65. This is raised whenever the maximum number of candidate solutions
  66. to consider specified by the ``max_work`` parameter is exceeded.
  67. Assigning a finite number to ``max_work`` may have caused the operation
  68. to fail.
  69. """
  70. pass
  71. class AxisError(ValueError, IndexError):
  72. """Axis supplied was invalid.
  73. This is raised whenever an ``axis`` parameter is specified that is larger
  74. than the number of array dimensions.
  75. For compatibility with code written against older numpy versions, which
  76. raised a mixture of :exc:`ValueError` and :exc:`IndexError` for this
  77. situation, this exception subclasses both to ensure that
  78. ``except ValueError`` and ``except IndexError`` statements continue
  79. to catch ``AxisError``.
  80. Parameters
  81. ----------
  82. axis : int or str
  83. The out of bounds axis or a custom exception message.
  84. If an axis is provided, then `ndim` should be specified as well.
  85. ndim : int, optional
  86. The number of array dimensions.
  87. msg_prefix : str, optional
  88. A prefix for the exception message.
  89. Attributes
  90. ----------
  91. axis : int, optional
  92. The out of bounds axis or ``None`` if a custom exception
  93. message was provided. This should be the axis as passed by
  94. the user, before any normalization to resolve negative indices.
  95. .. versionadded:: 1.22
  96. ndim : int, optional
  97. The number of array dimensions or ``None`` if a custom exception
  98. message was provided.
  99. .. versionadded:: 1.22
  100. Examples
  101. --------
  102. >>> import numpy as np
  103. >>> array_1d = np.arange(10)
  104. >>> np.cumsum(array_1d, axis=1)
  105. Traceback (most recent call last):
  106. ...
  107. numpy.exceptions.AxisError: axis 1 is out of bounds for array of dimension 1
  108. Negative axes are preserved:
  109. >>> np.cumsum(array_1d, axis=-2)
  110. Traceback (most recent call last):
  111. ...
  112. numpy.exceptions.AxisError: axis -2 is out of bounds for array of dimension 1
  113. The class constructor generally takes the axis and arrays'
  114. dimensionality as arguments:
  115. >>> print(np.exceptions.AxisError(2, 1, msg_prefix='error'))
  116. error: axis 2 is out of bounds for array of dimension 1
  117. Alternatively, a custom exception message can be passed:
  118. >>> print(np.exceptions.AxisError('Custom error message'))
  119. Custom error message
  120. """
  121. __slots__ = ("_msg", "axis", "ndim")
  122. def __init__(self, axis, ndim=None, msg_prefix=None):
  123. if ndim is msg_prefix is None:
  124. # single-argument form: directly set the error message
  125. self._msg = axis
  126. self.axis = None
  127. self.ndim = None
  128. else:
  129. self._msg = msg_prefix
  130. self.axis = axis
  131. self.ndim = ndim
  132. def __str__(self):
  133. axis = self.axis
  134. ndim = self.ndim
  135. if axis is ndim is None:
  136. return self._msg
  137. else:
  138. msg = f"axis {axis} is out of bounds for array of dimension {ndim}"
  139. if self._msg is not None:
  140. msg = f"{self._msg}: {msg}"
  141. return msg
  142. class DTypePromotionError(TypeError):
  143. """Multiple DTypes could not be converted to a common one.
  144. This exception derives from ``TypeError`` and is raised whenever dtypes
  145. cannot be converted to a single common one. This can be because they
  146. are of a different category/class or incompatible instances of the same
  147. one (see Examples).
  148. Notes
  149. -----
  150. Many functions will use promotion to find the correct result and
  151. implementation. For these functions the error will typically be chained
  152. with a more specific error indicating that no implementation was found
  153. for the input dtypes.
  154. Typically promotion should be considered "invalid" between the dtypes of
  155. two arrays when `arr1 == arr2` can safely return all ``False`` because the
  156. dtypes are fundamentally different.
  157. Examples
  158. --------
  159. Datetimes and complex numbers are incompatible classes and cannot be
  160. promoted:
  161. >>> import numpy as np
  162. >>> np.result_type(np.dtype("M8[s]"), np.complex128) # doctest: +IGNORE_EXCEPTION_DETAIL
  163. Traceback (most recent call last):
  164. ...
  165. DTypePromotionError: The DType <class 'numpy.dtype[datetime64]'> could not
  166. be promoted by <class 'numpy.dtype[complex128]'>. This means that no common
  167. DType exists for the given inputs. For example they cannot be stored in a
  168. single array unless the dtype is `object`. The full list of DTypes is:
  169. (<class 'numpy.dtype[datetime64]'>, <class 'numpy.dtype[complex128]'>)
  170. For example for structured dtypes, the structure can mismatch and the
  171. same ``DTypePromotionError`` is given when two structured dtypes with
  172. a mismatch in their number of fields is given:
  173. >>> dtype1 = np.dtype([("field1", np.float64), ("field2", np.int64)])
  174. >>> dtype2 = np.dtype([("field1", np.float64)])
  175. >>> np.promote_types(dtype1, dtype2) # doctest: +IGNORE_EXCEPTION_DETAIL
  176. Traceback (most recent call last):
  177. ...
  178. DTypePromotionError: field names `('field1', 'field2')` and `('field1',)`
  179. mismatch.
  180. """ # noqa: E501
  181. pass