exceptions.py 13 KB

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