Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/astroid/exceptions.py: 83%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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
5"""This module contains exceptions used in the astroid library."""
7from __future__ import annotations
9from collections.abc import Iterable, Iterator
10from typing import TYPE_CHECKING, Any
12if TYPE_CHECKING:
13 from astroid import arguments, bases, nodes, objects
14 from astroid.context import InferenceContext
15 from astroid.typing import InferenceResult, SuccessfulInferenceResult
17__all__ = (
18 "AstroidBuildingError",
19 "AstroidError",
20 "AstroidImportError",
21 "AstroidIndexError",
22 "AstroidSyntaxError",
23 "AstroidTypeError",
24 "AstroidValueError",
25 "AttributeInferenceError",
26 "DuplicateBasesError",
27 "InconsistentMroError",
28 "InferenceError",
29 "InferenceOverwriteError",
30 "MroError",
31 "NameInferenceError",
32 "NoDefault",
33 "NotFoundError",
34 "ParentMissingError",
35 "ResolveError",
36 "StatementMissing",
37 "SuperArgumentTypeError",
38 "SuperError",
39 "TooManyLevelsError",
40 "UnresolvableName",
41 "UseInferenceDefault",
42)
45class AstroidError(Exception):
46 """Base exception class for all astroid related exceptions.
48 AstroidError and its subclasses are structured, intended to hold
49 objects representing state when the exception is thrown. Field
50 values are passed to the constructor as keyword-only arguments.
51 Each subclass has its own set of standard fields, but use your
52 best judgment to decide whether a specific exception instance
53 needs more or fewer fields for debugging. Field values may be
54 used to lazily generate the error message: self.message.format()
55 will be called with the field names and values supplied as keyword
56 arguments.
57 """
59 def __init__(self, message: str = "", **kws: Any) -> None:
60 super().__init__(message)
61 self.message = message
62 for key, value in kws.items():
63 setattr(self, key, value)
65 def __str__(self) -> str:
66 try:
67 return self.message.format(**vars(self))
68 except ValueError:
69 return self.message # Return raw message if formatting fails
72class AstroidBuildingError(AstroidError):
73 """Exception class when we are unable to build an astroid representation.
75 Standard attributes:
76 modname: Name of the module that AST construction failed for.
77 error: Exception raised during construction.
78 """
80 def __init__(
81 self,
82 message: str = "Failed to import module {modname}.",
83 modname: str | None = None,
84 error: Exception | None = None,
85 source: str | None = None,
86 path: str | None = None,
87 cls: type | None = None,
88 class_repr: str | None = None,
89 **kws: Any,
90 ) -> None:
91 self.modname = modname
92 self.error = error
93 self.source = source
94 self.path = path
95 self.cls = cls
96 self.class_repr = class_repr
97 super().__init__(message, **kws)
100class AstroidImportError(AstroidBuildingError):
101 """Exception class used when a module can't be imported by astroid."""
104class TooManyLevelsError(AstroidImportError):
105 """Exception class which is raised when a relative import was beyond the top-level.
107 Standard attributes:
108 level: The level which was attempted.
109 name: the name of the module on which the relative import was attempted.
110 """
112 def __init__(
113 self,
114 message: str = "Relative import with too many levels "
115 "({level}) for module {name!r}",
116 level: int | None = None,
117 name: str | None = None,
118 **kws: Any,
119 ) -> None:
120 self.level = level
121 self.name = name
122 super().__init__(message, **kws)
125class AstroidSyntaxError(AstroidBuildingError):
126 """Exception class used when a module can't be parsed."""
128 def __init__(
129 self,
130 message: str,
131 modname: str | None,
132 error: Exception,
133 path: str | None,
134 source: str | None = None,
135 ) -> None:
136 super().__init__(message, modname, error, source, path)
139class NoDefault(AstroidError):
140 """Raised by function's `default_value` method when an argument has
141 no default value.
143 Standard attributes:
144 func: Function node.
145 name: Name of argument without a default.
146 """
148 def __init__(
149 self,
150 message: str = "{func!r} has no default for {name!r}.",
151 func: nodes.FunctionDef | None = None,
152 name: str | None = None,
153 **kws: Any,
154 ) -> None:
155 self.func = func
156 self.name = name
157 super().__init__(message, **kws)
160class ResolveError(AstroidError):
161 """Base class of astroid resolution/inference error.
163 ResolveError is not intended to be raised.
165 Standard attributes:
166 context: InferenceContext object.
167 """
169 def __init__(
170 self, message: str = "", context: InferenceContext | None = None, **kws: Any
171 ) -> None:
172 self.context = context
173 super().__init__(message, **kws)
176class MroError(ResolveError):
177 """Error raised when there is a problem with method resolution of a class.
179 Standard attributes:
180 mros: A sequence of sequences containing ClassDef nodes.
181 cls: ClassDef node whose MRO resolution failed.
182 context: InferenceContext object.
183 """
185 def __init__(
186 self,
187 message: str,
188 mros: Iterable[Iterable[nodes.ClassDef]],
189 cls: nodes.ClassDef,
190 context: InferenceContext | None = None,
191 **kws: Any,
192 ) -> None:
193 self.mros = mros
194 self.cls = cls
195 self.context = context
196 super().__init__(message, **kws)
198 def __str__(self) -> str:
199 mro_names = ", ".join(f"({', '.join(b.name for b in m)})" for m in self.mros)
200 return self.message.format(mros=mro_names, cls=self.cls)
203class DuplicateBasesError(MroError):
204 """Error raised when there are duplicate bases in the same class bases."""
207class InconsistentMroError(MroError):
208 """Error raised when a class's MRO is inconsistent."""
211class SuperError(ResolveError):
212 """Error raised when there is a problem with a *super* call.
214 Standard attributes:
215 *super_*: The Super instance that raised the exception.
216 context: InferenceContext object.
217 """
219 def __init__(self, message: str, super_: objects.Super, **kws: Any) -> None:
220 self.super_ = super_
221 super().__init__(message, **kws)
223 def __str__(self) -> str:
224 return self.message.format(**vars(self.super_))
227class InferenceError(ResolveError): # pylint: disable=too-many-instance-attributes
228 """Raised when we are unable to infer a node.
230 Standard attributes:
231 node: The node inference was called on.
232 context: InferenceContext object.
233 """
235 def __init__( # pylint: disable=too-many-arguments, too-many-positional-arguments
236 self,
237 message: str = "Inference failed for {node!r}.",
238 node: InferenceResult | None = None,
239 context: InferenceContext | None = None,
240 target: InferenceResult | None = None,
241 targets: InferenceResult | None = None,
242 attribute: str | None = None,
243 unknown: InferenceResult | None = None,
244 assign_path: list[int] | None = None,
245 caller: SuccessfulInferenceResult | None = None,
246 stmts: Iterator[InferenceResult] | None = None,
247 frame: InferenceResult | None = None,
248 call_site: arguments.CallSite | None = None,
249 func: InferenceResult | None = None,
250 arg: str | None = None,
251 positional_arguments: list | None = None,
252 unpacked_args: list | None = None,
253 keyword_arguments: dict | None = None,
254 unpacked_kwargs: dict | None = None,
255 **kws: Any,
256 ) -> None:
257 self.node = node
258 self.context = context
259 self.target = target
260 self.targets = targets
261 self.attribute = attribute
262 self.unknown = unknown
263 self.assign_path = assign_path
264 self.caller = caller
265 self.stmts = stmts
266 self.frame = frame
267 self.call_site = call_site
268 self.func = func
269 self.arg = arg
270 self.positional_arguments = positional_arguments
271 self.unpacked_args = unpacked_args
272 self.keyword_arguments = keyword_arguments
273 self.unpacked_kwargs = unpacked_kwargs
274 super().__init__(message, **kws)
277# Why does this inherit from InferenceError rather than ResolveError?
278# Changing it causes some inference tests to fail.
279class NameInferenceError(InferenceError):
280 """Raised when a name lookup fails, corresponds to NameError.
282 Standard attributes:
283 name: The name for which lookup failed, as a string.
284 scope: The node representing the scope in which the lookup occurred.
285 context: InferenceContext object.
286 """
288 def __init__(
289 self,
290 message: str = "{name!r} not found in {scope!r}.",
291 name: str | None = None,
292 scope: nodes.LocalsDictNodeNG | None = None,
293 context: InferenceContext | None = None,
294 **kws: Any,
295 ) -> None:
296 self.name = name
297 self.scope = scope
298 self.context = context
299 super().__init__(message, **kws)
302class AttributeInferenceError(ResolveError):
303 """Raised when an attribute lookup fails, corresponds to AttributeError.
305 Standard attributes:
306 target: The node for which lookup failed.
307 attribute: The attribute for which lookup failed, as a string.
308 context: InferenceContext object.
309 """
311 def __init__(
312 self,
313 message: str = "{attribute!r} not found on {target!r}.",
314 attribute: str = "",
315 target: nodes.NodeNG | bases.BaseInstance | None = None,
316 context: InferenceContext | None = None,
317 mros: list[nodes.ClassDef] | None = None,
318 super_: nodes.ClassDef | None = None,
319 cls: nodes.ClassDef | None = None,
320 **kws: Any,
321 ) -> None:
322 self.attribute = attribute
323 self.target = target
324 self.context = context
325 self.mros = mros
326 self.super_ = super_
327 self.cls = cls
328 super().__init__(message, **kws)
331class UseInferenceDefault(Exception):
332 """Exception to be raised in custom inference function to indicate that it
333 should go back to the default behaviour.
334 """
337class _NonDeducibleTypeHierarchy(Exception):
338 """Raised when is_subtype / is_supertype can't deduce the relation between two
339 types.
340 """
343class AstroidIndexError(AstroidError):
344 """Raised when an Indexable / Mapping does not have an index / key."""
346 def __init__(
347 self,
348 message: str = "",
349 node: nodes.NodeNG | bases.Instance | None = None,
350 index: nodes.Subscript | None = None,
351 context: InferenceContext | None = None,
352 **kws: Any,
353 ) -> None:
354 self.node = node
355 self.index = index
356 self.context = context
357 super().__init__(message, **kws)
360class AstroidTypeError(AstroidError):
361 """Raised when a TypeError would be expected in Python code."""
363 def __init__(
364 self,
365 message: str = "",
366 node: nodes.NodeNG | bases.Instance | None = None,
367 index: nodes.Subscript | None = None,
368 context: InferenceContext | None = None,
369 **kws: Any,
370 ) -> None:
371 self.node = node
372 self.index = index
373 self.context = context
374 super().__init__(message, **kws)
377class AstroidValueError(AstroidError):
378 """Raised when a ValueError would be expected in Python code."""
381class InferenceOverwriteError(AstroidError):
382 """Raised when an inference tip is overwritten.
384 Currently only used for debugging.
385 """
388class ParentMissingError(AstroidError):
389 """Raised when a node which is expected to have a parent attribute is missing one.
391 Standard attributes:
392 target: The node for which the parent lookup failed.
393 """
395 def __init__(self, target: nodes.NodeNG) -> None:
396 self.target = target
397 super().__init__(message=f"Parent not found on {target!r}.")
400class StatementMissing(ParentMissingError):
401 """Raised when a call to node.statement() does not return a node.
403 This is because a node in the chain does not have a parent attribute
404 and therefore does not return a node for statement().
406 Standard attributes:
407 target: The node for which the parent lookup failed.
408 """
410 def __init__(self, target: nodes.NodeNG) -> None:
411 super(ParentMissingError, self).__init__(
412 message=f"Statement not found on {target!r}"
413 )
416SuperArgumentTypeError = SuperError
417UnresolvableName = NameInferenceError
418NotFoundError = AttributeInferenceError