exceptions.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. # Copyright (c) 2007, 2009-2010, 2013 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  2. # Copyright (c) 2014 Google, Inc.
  3. # Copyright (c) 2015-2018, 2020 Claudiu Popa <pcmanticore@gmail.com>
  4. # Copyright (c) 2015-2016 Ceridwen <ceridwenv@gmail.com>
  5. # Copyright (c) 2016 Derek Gustafson <degustaf@gmail.com>
  6. # Copyright (c) 2018 Bryce Guinta <bryce.paul.guinta@gmail.com>
  7. # Copyright (c) 2020-2021 hippo91 <guillaume.peillex@gmail.com>
  8. # Copyright (c) 2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
  9. # Copyright (c) 2021 Daniël van Noord <13665637+DanielNoord@users.noreply.github.com>
  10. # Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com>
  11. # Copyright (c) 2021 Andrew Haigh <hello@nelf.in>
  12. # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
  13. # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
  14. """this module contains exceptions used in the astroid library
  15. """
  16. from typing import TYPE_CHECKING
  17. from astroid import util
  18. if TYPE_CHECKING:
  19. from astroid import nodes
  20. __all__ = (
  21. "AstroidBuildingError",
  22. "AstroidBuildingException",
  23. "AstroidError",
  24. "AstroidImportError",
  25. "AstroidIndexError",
  26. "AstroidSyntaxError",
  27. "AstroidTypeError",
  28. "AstroidValueError",
  29. "AttributeInferenceError",
  30. "BinaryOperationError",
  31. "DuplicateBasesError",
  32. "InconsistentMroError",
  33. "InferenceError",
  34. "InferenceOverwriteError",
  35. "MroError",
  36. "NameInferenceError",
  37. "NoDefault",
  38. "NotFoundError",
  39. "OperationError",
  40. "ResolveError",
  41. "SuperArgumentTypeError",
  42. "SuperError",
  43. "TooManyLevelsError",
  44. "UnaryOperationError",
  45. "UnresolvableName",
  46. "UseInferenceDefault",
  47. )
  48. class AstroidError(Exception):
  49. """base exception class for all astroid related exceptions
  50. AstroidError and its subclasses are structured, intended to hold
  51. objects representing state when the exception is thrown. Field
  52. values are passed to the constructor as keyword-only arguments.
  53. Each subclass has its own set of standard fields, but use your
  54. best judgment to decide whether a specific exception instance
  55. needs more or fewer fields for debugging. Field values may be
  56. used to lazily generate the error message: self.message.format()
  57. will be called with the field names and values supplied as keyword
  58. arguments.
  59. """
  60. def __init__(self, message="", **kws):
  61. super().__init__(message)
  62. self.message = message
  63. for key, value in kws.items():
  64. setattr(self, key, value)
  65. def __str__(self):
  66. return self.message.format(**vars(self))
  67. class AstroidBuildingError(AstroidError):
  68. """exception class when we are unable to build an astroid representation
  69. Standard attributes:
  70. modname: Name of the module that AST construction failed for.
  71. error: Exception raised during construction.
  72. """
  73. def __init__(self, message="Failed to import module {modname}.", **kws):
  74. super().__init__(message, **kws)
  75. class AstroidImportError(AstroidBuildingError):
  76. """Exception class used when a module can't be imported by astroid."""
  77. class TooManyLevelsError(AstroidImportError):
  78. """Exception class which is raised when a relative import was beyond the top-level.
  79. Standard attributes:
  80. level: The level which was attempted.
  81. name: the name of the module on which the relative import was attempted.
  82. """
  83. level = None
  84. name = None
  85. def __init__(
  86. self,
  87. message="Relative import with too many levels " "({level}) for module {name!r}",
  88. **kws,
  89. ):
  90. super().__init__(message, **kws)
  91. class AstroidSyntaxError(AstroidBuildingError):
  92. """Exception class used when a module can't be parsed."""
  93. class NoDefault(AstroidError):
  94. """raised by function's `default_value` method when an argument has
  95. no default value
  96. Standard attributes:
  97. func: Function node.
  98. name: Name of argument without a default.
  99. """
  100. func = None
  101. name = None
  102. def __init__(self, message="{func!r} has no default for {name!r}.", **kws):
  103. super().__init__(message, **kws)
  104. class ResolveError(AstroidError):
  105. """Base class of astroid resolution/inference error.
  106. ResolveError is not intended to be raised.
  107. Standard attributes:
  108. context: InferenceContext object.
  109. """
  110. context = None
  111. class MroError(ResolveError):
  112. """Error raised when there is a problem with method resolution of a class.
  113. Standard attributes:
  114. mros: A sequence of sequences containing ClassDef nodes.
  115. cls: ClassDef node whose MRO resolution failed.
  116. context: InferenceContext object.
  117. """
  118. mros = ()
  119. cls = None
  120. def __str__(self):
  121. mro_names = ", ".join(f"({', '.join(b.name for b in m)})" for m in self.mros)
  122. return self.message.format(mros=mro_names, cls=self.cls)
  123. class DuplicateBasesError(MroError):
  124. """Error raised when there are duplicate bases in the same class bases."""
  125. class InconsistentMroError(MroError):
  126. """Error raised when a class's MRO is inconsistent."""
  127. class SuperError(ResolveError):
  128. """Error raised when there is a problem with a *super* call.
  129. Standard attributes:
  130. *super_*: The Super instance that raised the exception.
  131. context: InferenceContext object.
  132. """
  133. super_ = None
  134. def __str__(self):
  135. return self.message.format(**vars(self.super_))
  136. class InferenceError(ResolveError):
  137. """raised when we are unable to infer a node
  138. Standard attributes:
  139. node: The node inference was called on.
  140. context: InferenceContext object.
  141. """
  142. node = None
  143. context = None
  144. def __init__(self, message="Inference failed for {node!r}.", **kws):
  145. super().__init__(message, **kws)
  146. # Why does this inherit from InferenceError rather than ResolveError?
  147. # Changing it causes some inference tests to fail.
  148. class NameInferenceError(InferenceError):
  149. """Raised when a name lookup fails, corresponds to NameError.
  150. Standard attributes:
  151. name: The name for which lookup failed, as a string.
  152. scope: The node representing the scope in which the lookup occurred.
  153. context: InferenceContext object.
  154. """
  155. name = None
  156. scope = None
  157. def __init__(self, message="{name!r} not found in {scope!r}.", **kws):
  158. super().__init__(message, **kws)
  159. class AttributeInferenceError(ResolveError):
  160. """Raised when an attribute lookup fails, corresponds to AttributeError.
  161. Standard attributes:
  162. target: The node for which lookup failed.
  163. attribute: The attribute for which lookup failed, as a string.
  164. context: InferenceContext object.
  165. """
  166. target = None
  167. attribute = None
  168. def __init__(self, message="{attribute!r} not found on {target!r}.", **kws):
  169. super().__init__(message, **kws)
  170. class UseInferenceDefault(Exception):
  171. """exception to be raised in custom inference function to indicate that it
  172. should go back to the default behaviour
  173. """
  174. class _NonDeducibleTypeHierarchy(Exception):
  175. """Raised when is_subtype / is_supertype can't deduce the relation between two types."""
  176. class AstroidIndexError(AstroidError):
  177. """Raised when an Indexable / Mapping does not have an index / key."""
  178. class AstroidTypeError(AstroidError):
  179. """Raised when a TypeError would be expected in Python code."""
  180. class AstroidValueError(AstroidError):
  181. """Raised when a ValueError would be expected in Python code."""
  182. class InferenceOverwriteError(AstroidError):
  183. """Raised when an inference tip is overwritten
  184. Currently only used for debugging.
  185. """
  186. class ParentMissingError(AstroidError):
  187. """Raised when a node which is expected to have a parent attribute is missing one
  188. Standard attributes:
  189. target: The node for which the parent lookup failed.
  190. """
  191. def __init__(self, target: "nodes.NodeNG") -> None:
  192. self.target = target
  193. super().__init__(message=f"Parent not found on {target!r}.")
  194. class StatementMissing(ParentMissingError):
  195. """Raised when a call to node.statement() does not return a node. This is because
  196. a node in the chain does not have a parent attribute and therefore does not
  197. return a node for statement().
  198. Standard attributes:
  199. target: The node for which the parent lookup failed.
  200. """
  201. def __init__(self, target: "nodes.NodeNG") -> None:
  202. # pylint: disable-next=bad-super-call
  203. # https://github.com/PyCQA/pylint/issues/2903
  204. # https://github.com/PyCQA/astroid/pull/1217#discussion_r744149027
  205. super(ParentMissingError, self).__init__(
  206. message=f"Statement not found on {target!r}"
  207. )
  208. # Backwards-compatibility aliases
  209. OperationError = util.BadOperationMessage
  210. UnaryOperationError = util.BadUnaryOperationMessage
  211. BinaryOperationError = util.BadBinaryOperationMessage
  212. SuperArgumentTypeError = SuperError
  213. UnresolvableName = NameInferenceError
  214. NotFoundError = AttributeInferenceError
  215. AstroidBuildingException = AstroidBuildingError