exceptions.py 7.7 KB

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