exceptions.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
  2. # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
  3. # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
  4. """This module contains exceptions used in the astroid library."""
  5. from __future__ import annotations
  6. from collections.abc import Sequence
  7. from typing import TYPE_CHECKING, Any
  8. from astroid import util
  9. if TYPE_CHECKING:
  10. from astroid import arguments, bases, nodes, objects
  11. from astroid.context import InferenceContext
  12. __all__ = (
  13. "AstroidBuildingError",
  14. "AstroidBuildingException",
  15. "AstroidError",
  16. "AstroidImportError",
  17. "AstroidIndexError",
  18. "AstroidSyntaxError",
  19. "AstroidTypeError",
  20. "AstroidValueError",
  21. "AttributeInferenceError",
  22. "BinaryOperationError",
  23. "DuplicateBasesError",
  24. "InconsistentMroError",
  25. "InferenceError",
  26. "InferenceOverwriteError",
  27. "MroError",
  28. "NameInferenceError",
  29. "NoDefault",
  30. "NotFoundError",
  31. "OperationError",
  32. "ParentMissingError",
  33. "ResolveError",
  34. "StatementMissing",
  35. "SuperArgumentTypeError",
  36. "SuperError",
  37. "TooManyLevelsError",
  38. "UnaryOperationError",
  39. "UnresolvableName",
  40. "UseInferenceDefault",
  41. )
  42. class AstroidError(Exception):
  43. """Base exception class for all astroid related exceptions.
  44. AstroidError and its subclasses are structured, intended to hold
  45. objects representing state when the exception is thrown. Field
  46. values are passed to the constructor as keyword-only arguments.
  47. Each subclass has its own set of standard fields, but use your
  48. best judgment to decide whether a specific exception instance
  49. needs more or fewer fields for debugging. Field values may be
  50. used to lazily generate the error message: self.message.format()
  51. will be called with the field names and values supplied as keyword
  52. arguments.
  53. """
  54. def __init__(self, message: str = "", **kws: Any) -> None:
  55. super().__init__(message)
  56. self.message = message
  57. for key, value in kws.items():
  58. setattr(self, key, value)
  59. def __str__(self) -> str:
  60. return self.message.format(**vars(self))
  61. class AstroidBuildingError(AstroidError):
  62. """Exception class when we are unable to build an astroid representation.
  63. Standard attributes:
  64. modname: Name of the module that AST construction failed for.
  65. error: Exception raised during construction.
  66. """
  67. def __init__(
  68. self,
  69. message: str = "Failed to import module {modname}.",
  70. modname: str | None = None,
  71. error: Exception | None = None,
  72. source: str | None = None,
  73. path: str | None = None,
  74. cls: type | None = None,
  75. class_repr: str | None = None,
  76. **kws: Any,
  77. ) -> None:
  78. self.modname = modname
  79. self.error = error
  80. self.source = source
  81. self.path = path
  82. self.cls = cls
  83. self.class_repr = class_repr
  84. super().__init__(message, **kws)
  85. class AstroidImportError(AstroidBuildingError):
  86. """Exception class used when a module can't be imported by astroid."""
  87. class TooManyLevelsError(AstroidImportError):
  88. """Exception class which is raised when a relative import was beyond the top-level.
  89. Standard attributes:
  90. level: The level which was attempted.
  91. name: the name of the module on which the relative import was attempted.
  92. """
  93. def __init__(
  94. self,
  95. message: str = "Relative import with too many levels "
  96. "({level}) for module {name!r}",
  97. level: int | None = None,
  98. name: str | None = None,
  99. **kws: Any,
  100. ) -> None:
  101. self.level = level
  102. self.name = name
  103. super().__init__(message, **kws)
  104. class AstroidSyntaxError(AstroidBuildingError):
  105. """Exception class used when a module can't be parsed."""
  106. def __init__(
  107. self,
  108. message: str,
  109. modname: str | None,
  110. error: Exception,
  111. path: str | None,
  112. source: str | None = None,
  113. ) -> None:
  114. super().__init__(message, modname, error, source, path)
  115. class NoDefault(AstroidError):
  116. """Raised by function's `default_value` method when an argument has
  117. no default value.
  118. Standard attributes:
  119. func: Function node.
  120. name: Name of argument without a default.
  121. """
  122. def __init__(
  123. self,
  124. message: str = "{func!r} has no default for {name!r}.",
  125. func: nodes.FunctionDef | None = None,
  126. name: str | None = None,
  127. **kws: Any,
  128. ) -> None:
  129. self.func = func
  130. self.name = name
  131. super().__init__(message, **kws)
  132. class ResolveError(AstroidError):
  133. """Base class of astroid resolution/inference error.
  134. ResolveError is not intended to be raised.
  135. Standard attributes:
  136. context: InferenceContext object.
  137. """
  138. def __init__(
  139. self, message: str = "", context: InferenceContext | None = None, **kws: Any
  140. ) -> None:
  141. self.context = context
  142. super().__init__(message, **kws)
  143. class MroError(ResolveError):
  144. """Error raised when there is a problem with method resolution of a class.
  145. Standard attributes:
  146. mros: A sequence of sequences containing ClassDef nodes.
  147. cls: ClassDef node whose MRO resolution failed.
  148. context: InferenceContext object.
  149. """
  150. def __init__(
  151. self,
  152. message: str,
  153. mros: list[nodes.ClassDef],
  154. cls: nodes.ClassDef,
  155. context: InferenceContext | None = None,
  156. **kws: Any,
  157. ) -> None:
  158. self.mros = mros
  159. self.cls = cls
  160. self.context = context
  161. super().__init__(message, **kws)
  162. def __str__(self) -> str:
  163. mro_names = ", ".join(f"({', '.join(b.name for b in m)})" for m in self.mros)
  164. return self.message.format(mros=mro_names, cls=self.cls)
  165. class DuplicateBasesError(MroError):
  166. """Error raised when there are duplicate bases in the same class bases."""
  167. class InconsistentMroError(MroError):
  168. """Error raised when a class's MRO is inconsistent."""
  169. class SuperError(ResolveError):
  170. """Error raised when there is a problem with a *super* call.
  171. Standard attributes:
  172. *super_*: The Super instance that raised the exception.
  173. context: InferenceContext object.
  174. """
  175. def __init__(self, message: str, super_: objects.Super, **kws: Any) -> None:
  176. self.super_ = super_
  177. super().__init__(message, **kws)
  178. def __str__(self) -> str:
  179. return self.message.format(**vars(self.super_))
  180. class InferenceError(ResolveError): # pylint: disable=too-many-instance-attributes
  181. """Raised when we are unable to infer a node.
  182. Standard attributes:
  183. node: The node inference was called on.
  184. context: InferenceContext object.
  185. """
  186. def __init__( # pylint: disable=too-many-arguments
  187. self,
  188. message: str = "Inference failed for {node!r}.",
  189. node: nodes.NodeNG | bases.Instance | None = None,
  190. context: InferenceContext | None = None,
  191. target: nodes.NodeNG | bases.Instance | None = None,
  192. targets: nodes.Tuple | None = None,
  193. attribute: str | None = None,
  194. unknown: nodes.NodeNG | bases.Instance | None = None,
  195. assign_path: list[int] | None = None,
  196. caller: nodes.Call | None = None,
  197. stmts: Sequence[nodes.NodeNG | bases.Instance] | None = None,
  198. frame: nodes.LocalsDictNodeNG | None = None,
  199. call_site: arguments.CallSite | None = None,
  200. func: nodes.FunctionDef | None = None,
  201. arg: str | None = None,
  202. positional_arguments: list | None = None,
  203. unpacked_args: list | None = None,
  204. keyword_arguments: dict | None = None,
  205. unpacked_kwargs: dict | None = None,
  206. **kws: Any,
  207. ) -> None:
  208. self.node = node
  209. self.context = context
  210. self.target = target
  211. self.targets = targets
  212. self.attribute = attribute
  213. self.unknown = unknown
  214. self.assign_path = assign_path
  215. self.caller = caller
  216. self.stmts = stmts
  217. self.frame = frame
  218. self.call_site = call_site
  219. self.func = func
  220. self.arg = arg
  221. self.positional_arguments = positional_arguments
  222. self.unpacked_args = unpacked_args
  223. self.keyword_arguments = keyword_arguments
  224. self.unpacked_kwargs = unpacked_kwargs
  225. super().__init__(message, **kws)
  226. # Why does this inherit from InferenceError rather than ResolveError?
  227. # Changing it causes some inference tests to fail.
  228. class NameInferenceError(InferenceError):
  229. """Raised when a name lookup fails, corresponds to NameError.
  230. Standard attributes:
  231. name: The name for which lookup failed, as a string.
  232. scope: The node representing the scope in which the lookup occurred.
  233. context: InferenceContext object.
  234. """
  235. def __init__(
  236. self,
  237. message: str = "{name!r} not found in {scope!r}.",
  238. name: str | None = None,
  239. scope: nodes.LocalsDictNodeNG | None = None,
  240. context: InferenceContext | None = None,
  241. **kws: Any,
  242. ) -> None:
  243. self.name = name
  244. self.scope = scope
  245. self.context = context
  246. super().__init__(message, **kws)
  247. class AttributeInferenceError(ResolveError):
  248. """Raised when an attribute lookup fails, corresponds to AttributeError.
  249. Standard attributes:
  250. target: The node for which lookup failed.
  251. attribute: The attribute for which lookup failed, as a string.
  252. context: InferenceContext object.
  253. """
  254. def __init__(
  255. self,
  256. message: str = "{attribute!r} not found on {target!r}.",
  257. attribute: str = "",
  258. target: nodes.NodeNG | bases.Instance | None = None,
  259. context: InferenceContext | None = None,
  260. mros: list[nodes.ClassDef] | None = None,
  261. super_: nodes.ClassDef | None = None,
  262. cls: nodes.ClassDef | None = None,
  263. **kws: Any,
  264. ) -> None:
  265. self.attribute = attribute
  266. self.target = target
  267. self.context = context
  268. self.mros = mros
  269. self.super_ = super_
  270. self.cls = cls
  271. super().__init__(message, **kws)
  272. class UseInferenceDefault(Exception):
  273. """Exception to be raised in custom inference function to indicate that it
  274. should go back to the default behaviour.
  275. """
  276. class _NonDeducibleTypeHierarchy(Exception):
  277. """Raised when is_subtype / is_supertype can't deduce the relation between two
  278. types.
  279. """
  280. class AstroidIndexError(AstroidError):
  281. """Raised when an Indexable / Mapping does not have an index / key."""
  282. def __init__(
  283. self,
  284. message: str = "",
  285. node: nodes.NodeNG | bases.Instance | None = None,
  286. index: nodes.Subscript | None = None,
  287. context: InferenceContext | None = None,
  288. **kws: Any,
  289. ) -> None:
  290. self.node = node
  291. self.index = index
  292. self.context = context
  293. super().__init__(message, **kws)
  294. class AstroidTypeError(AstroidError):
  295. """Raised when a TypeError would be expected in Python code."""
  296. def __init__(
  297. self,
  298. message: str = "",
  299. node: nodes.NodeNG | bases.Instance | None = None,
  300. index: nodes.Subscript | None = None,
  301. context: InferenceContext | None = None,
  302. **kws: Any,
  303. ) -> None:
  304. self.node = node
  305. self.index = index
  306. self.context = context
  307. super().__init__(message, **kws)
  308. class AstroidValueError(AstroidError):
  309. """Raised when a ValueError would be expected in Python code."""
  310. class InferenceOverwriteError(AstroidError):
  311. """Raised when an inference tip is overwritten.
  312. Currently only used for debugging.
  313. """
  314. class ParentMissingError(AstroidError):
  315. """Raised when a node which is expected to have a parent attribute is missing one.
  316. Standard attributes:
  317. target: The node for which the parent lookup failed.
  318. """
  319. def __init__(self, target: nodes.NodeNG) -> None:
  320. self.target = target
  321. super().__init__(message=f"Parent not found on {target!r}.")
  322. class StatementMissing(ParentMissingError):
  323. """Raised when a call to node.statement() does not return a node.
  324. This is because a node in the chain does not have a parent attribute
  325. and therefore does not return a node for statement().
  326. Standard attributes:
  327. target: The node for which the parent lookup failed.
  328. """
  329. def __init__(self, target: nodes.NodeNG) -> None:
  330. super(ParentMissingError, self).__init__(
  331. message=f"Statement not found on {target!r}"
  332. )
  333. # Backwards-compatibility aliases
  334. OperationError = util.BadOperationMessage
  335. UnaryOperationError = util.BadUnaryOperationMessage
  336. BinaryOperationError = util.BadBinaryOperationMessage
  337. SuperArgumentTypeError = SuperError
  338. UnresolvableName = NameInferenceError
  339. NotFoundError = AttributeInferenceError
  340. AstroidBuildingException = AstroidBuildingError