exceptions.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. 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. class VisibleDeprecationWarning(UserWarning):
  50. """Visible deprecation warning.
  51. By default, python will not show deprecation warnings, so this class
  52. can be used when a very visible warning is helpful, for example because
  53. the usage is most likely a user bug.
  54. """
  55. # Exception used in shares_memory()
  56. class TooHardError(RuntimeError):
  57. """max_work was exceeded.
  58. This is raised whenever the maximum number of candidate solutions
  59. to consider specified by the ``max_work`` parameter is exceeded.
  60. Assigning a finite number to max_work may have caused the operation
  61. to fail.
  62. """
  63. pass
  64. class AxisError(ValueError, IndexError):
  65. """Axis supplied was invalid.
  66. This is raised whenever an ``axis`` parameter is specified that is larger
  67. than the number of array dimensions.
  68. For compatibility with code written against older numpy versions, which
  69. raised a mixture of `ValueError` and `IndexError` for this situation, this
  70. exception subclasses both to ensure that ``except ValueError`` and
  71. ``except IndexError`` statements continue to catch `AxisError`.
  72. .. versionadded:: 1.13
  73. Parameters
  74. ----------
  75. axis : int or str
  76. The out of bounds axis or a custom exception message.
  77. If an axis is provided, then `ndim` should be specified as well.
  78. ndim : int, optional
  79. The number of array dimensions.
  80. msg_prefix : str, optional
  81. A prefix for the exception message.
  82. Attributes
  83. ----------
  84. axis : int, optional
  85. The out of bounds axis or ``None`` if a custom exception
  86. message was provided. This should be the axis as passed by
  87. the user, before any normalization to resolve negative indices.
  88. .. versionadded:: 1.22
  89. ndim : int, optional
  90. The number of array dimensions or ``None`` if a custom exception
  91. message was provided.
  92. .. versionadded:: 1.22
  93. Examples
  94. --------
  95. >>> array_1d = np.arange(10)
  96. >>> np.cumsum(array_1d, axis=1)
  97. Traceback (most recent call last):
  98. ...
  99. numpy.exceptions.AxisError: axis 1 is out of bounds for array of dimension 1
  100. Negative axes are preserved:
  101. >>> np.cumsum(array_1d, axis=-2)
  102. Traceback (most recent call last):
  103. ...
  104. numpy.exceptions.AxisError: axis -2 is out of bounds for array of dimension 1
  105. The class constructor generally takes the axis and arrays'
  106. dimensionality as arguments:
  107. >>> print(np.AxisError(2, 1, msg_prefix='error'))
  108. error: axis 2 is out of bounds for array of dimension 1
  109. Alternatively, a custom exception message can be passed:
  110. >>> print(np.AxisError('Custom error message'))
  111. Custom error message
  112. """
  113. __slots__ = ("axis", "ndim", "_msg")
  114. def __init__(self, axis, ndim=None, msg_prefix=None):
  115. if ndim is msg_prefix is None:
  116. # single-argument form: directly set the error message
  117. self._msg = axis
  118. self.axis = None
  119. self.ndim = None
  120. else:
  121. self._msg = msg_prefix
  122. self.axis = axis
  123. self.ndim = ndim
  124. def __str__(self):
  125. axis = self.axis
  126. ndim = self.ndim
  127. if axis is ndim is None:
  128. return self._msg
  129. else:
  130. msg = f"axis {axis} is out of bounds for array of dimension {ndim}"
  131. if self._msg is not None:
  132. msg = f"{self._msg}: {msg}"
  133. return msg
  134. class DTypePromotionError(TypeError):
  135. """Multiple DTypes could not be converted to a common one.
  136. This exception derives from ``TypeError`` and is raised whenever dtypes
  137. cannot be converted to a single common one. This can be because they
  138. are of a different category/class or incompatible instances of the same
  139. one (see Examples).
  140. Notes
  141. -----
  142. Many functions will use promotion to find the correct result and
  143. implementation. For these functions the error will typically be chained
  144. with a more specific error indicating that no implementation was found
  145. for the input dtypes.
  146. Typically promotion should be considered "invalid" between the dtypes of
  147. two arrays when `arr1 == arr2` can safely return all ``False`` because the
  148. dtypes are fundamentally different.
  149. Examples
  150. --------
  151. Datetimes and complex numbers are incompatible classes and cannot be
  152. promoted:
  153. >>> np.result_type(np.dtype("M8[s]"), np.complex128)
  154. DTypePromotionError: The DType <class 'numpy.dtype[datetime64]'> could not
  155. be promoted by <class 'numpy.dtype[complex128]'>. This means that no common
  156. DType exists for the given inputs. For example they cannot be stored in a
  157. single array unless the dtype is `object`. The full list of DTypes is:
  158. (<class 'numpy.dtype[datetime64]'>, <class 'numpy.dtype[complex128]'>)
  159. For example for structured dtypes, the structure can mismatch and the
  160. same ``DTypePromotionError`` is given when two structured dtypes with
  161. a mismatch in their number of fields is given:
  162. >>> dtype1 = np.dtype([("field1", np.float64), ("field2", np.int64)])
  163. >>> dtype2 = np.dtype([("field1", np.float64)])
  164. >>> np.promote_types(dtype1, dtype2)
  165. DTypePromotionError: field names `('field1', 'field2')` and `('field1',)`
  166. mismatch.
  167. """
  168. pass