Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/astroid/exceptions.py: 81%
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 # message is the template itself and may embed interpolated user text
67 # (e.g. a namedtuple typename), so keep it out of the fields and fall
68 # back to it verbatim rather than raising or reinterpreting it.
69 fields = {k: v for k, v in vars(self).items() if k != "message"}
70 try:
71 return self.message.format(**fields)
72 except (LookupError, ValueError, AttributeError, TypeError):
73 return self.message
76class AstroidBuildingError(AstroidError):
77 """Exception class when we are unable to build an astroid representation.
79 Standard attributes:
80 modname: Name of the module that AST construction failed for.
81 error: Exception raised during construction.
82 """
84 def __init__(
85 self,
86 message: str = "Failed to import module {modname}.",
87 modname: str | None = None,
88 error: Exception | None = None,
89 source: str | None = None,
90 path: str | None = None,
91 cls: type | None = None,
92 class_repr: str | None = None,
93 **kws: Any,
94 ) -> None:
95 self.modname = modname
96 self.error = error
97 self.source = source
98 self.path = path
99 self.cls = cls
100 self.class_repr = class_repr
101 super().__init__(message, **kws)
104class AstroidImportError(AstroidBuildingError):
105 """Exception class used when a module can't be imported by astroid."""
108class TooManyLevelsError(AstroidImportError):
109 """Exception class which is raised when a relative import was beyond the top-level.
111 Standard attributes:
112 level: The level which was attempted.
113 name: the name of the module on which the relative import was attempted.
114 """
116 def __init__(
117 self,
118 message: str = "Relative import with too many levels "
119 "({level}) for module {name!r}",
120 level: int | None = None,
121 name: str | None = None,
122 **kws: Any,
123 ) -> None:
124 self.level = level
125 self.name = name
126 super().__init__(message, **kws)
129class AstroidSyntaxError(AstroidBuildingError):
130 """Exception class used when a module can't be parsed."""
132 def __init__(
133 self,
134 message: str,
135 modname: str | None,
136 error: Exception,
137 path: str | None,
138 source: str | None = None,
139 ) -> None:
140 super().__init__(message, modname, error, source, path)
143class NoDefault(AstroidError):
144 """Raised by function's `default_value` method when an argument has
145 no default value.
147 Standard attributes:
148 func: Function node.
149 name: Name of argument without a default.
150 """
152 def __init__(
153 self,
154 message: str = "{func!r} has no default for {name!r}.",
155 func: nodes.FunctionDef | None = None,
156 name: str | None = None,
157 **kws: Any,
158 ) -> None:
159 self.func = func
160 self.name = name
161 super().__init__(message, **kws)
164class ResolveError(AstroidError):
165 """Base class of astroid resolution/inference error.
167 ResolveError is not intended to be raised.
169 Standard attributes:
170 context: InferenceContext object.
171 """
173 def __init__(
174 self, message: str = "", context: InferenceContext | None = None, **kws: Any
175 ) -> None:
176 self.context = context
177 super().__init__(message, **kws)
180class MroError(ResolveError):
181 """Error raised when there is a problem with method resolution of a class.
183 Standard attributes:
184 mros: A sequence of sequences containing ClassDef nodes.
185 cls: ClassDef node whose MRO resolution failed.
186 context: InferenceContext object.
187 """
189 def __init__(
190 self,
191 message: str,
192 mros: Iterable[Iterable[nodes.ClassDef]],
193 cls: nodes.ClassDef,
194 context: InferenceContext | None = None,
195 **kws: Any,
196 ) -> None:
197 self.mros = mros
198 self.cls = cls
199 self.context = context
200 super().__init__(message, **kws)
202 def __str__(self) -> str:
203 mro_names = ", ".join(f"({', '.join(b.name for b in m)})" for m in self.mros)
204 return self.message.format(mros=mro_names, cls=self.cls)
207class DuplicateBasesError(MroError):
208 """Error raised when there are duplicate bases in the same class bases."""
211class InconsistentMroError(MroError):
212 """Error raised when a class's MRO is inconsistent."""
215class SuperError(ResolveError):
216 """Error raised when there is a problem with a *super* call.
218 Standard attributes:
219 *super_*: The Super instance that raised the exception.
220 context: InferenceContext object.
221 """
223 def __init__(self, message: str, super_: objects.Super, **kws: Any) -> None:
224 self.super_ = super_
225 super().__init__(message, **kws)
227 def __str__(self) -> str:
228 return self.message.format(**vars(self.super_))
231class InferenceError(ResolveError): # pylint: disable=too-many-instance-attributes
232 """Raised when we are unable to infer a node.
234 Standard attributes:
235 node: The node inference was called on.
236 context: InferenceContext object.
237 """
239 def __init__( # pylint: disable=too-many-arguments, too-many-positional-arguments
240 self,
241 message: str = "Inference failed for {node!r}.",
242 node: InferenceResult | None = None,
243 context: InferenceContext | None = None,
244 target: InferenceResult | None = None,
245 targets: InferenceResult | None = None,
246 attribute: str | None = None,
247 unknown: InferenceResult | None = None,
248 assign_path: list[int] | None = None,
249 caller: SuccessfulInferenceResult | None = None,
250 stmts: Iterator[InferenceResult] | None = None,
251 frame: InferenceResult | None = None,
252 call_site: arguments.CallSite | None = None,
253 func: InferenceResult | None = None,
254 arg: str | None = None,
255 positional_arguments: list | None = None,
256 unpacked_args: list | None = None,
257 keyword_arguments: dict | None = None,
258 unpacked_kwargs: dict | None = None,
259 **kws: Any,
260 ) -> None:
261 self.node = node
262 self.context = context
263 self.target = target
264 self.targets = targets
265 self.attribute = attribute
266 self.unknown = unknown
267 self.assign_path = assign_path
268 self.caller = caller
269 self.stmts = stmts
270 self.frame = frame
271 self.call_site = call_site
272 self.func = func
273 self.arg = arg
274 self.positional_arguments = positional_arguments
275 self.unpacked_args = unpacked_args
276 self.keyword_arguments = keyword_arguments
277 self.unpacked_kwargs = unpacked_kwargs
278 super().__init__(message, **kws)
281# Why does this inherit from InferenceError rather than ResolveError?
282# Changing it causes some inference tests to fail.
283class NameInferenceError(InferenceError):
284 """Raised when a name lookup fails, corresponds to NameError.
286 Standard attributes:
287 name: The name for which lookup failed, as a string.
288 scope: The node representing the scope in which the lookup occurred.
289 context: InferenceContext object.
290 """
292 def __init__(
293 self,
294 message: str = "{name!r} not found in {scope!r}.",
295 name: str | None = None,
296 scope: nodes.LocalsDictNodeNG | None = None,
297 context: InferenceContext | None = None,
298 **kws: Any,
299 ) -> None:
300 self.name = name
301 self.scope = scope
302 self.context = context
303 super().__init__(message, **kws)
306class AttributeInferenceError(ResolveError):
307 """Raised when an attribute lookup fails, corresponds to AttributeError.
309 Standard attributes:
310 target: The node for which lookup failed.
311 attribute: The attribute for which lookup failed, as a string.
312 context: InferenceContext object.
313 """
315 def __init__(
316 self,
317 message: str = "{attribute!r} not found on {target!r}.",
318 attribute: str = "",
319 target: nodes.NodeNG | bases.BaseInstance | None = None,
320 context: InferenceContext | None = None,
321 mros: list[nodes.ClassDef] | None = None,
322 super_: nodes.ClassDef | None = None,
323 cls: nodes.ClassDef | None = None,
324 **kws: Any,
325 ) -> None:
326 self.attribute = attribute
327 self.target = target
328 self.context = context
329 self.mros = mros
330 self.super_ = super_
331 self.cls = cls
332 super().__init__(message, **kws)
335class UseInferenceDefault(Exception):
336 """Exception to be raised in custom inference function to indicate that it
337 should go back to the default behaviour.
338 """
341class _NonDeducibleTypeHierarchy(Exception):
342 """Raised when is_subtype / is_supertype can't deduce the relation between two
343 types.
344 """
347class AstroidIndexError(AstroidError):
348 """Raised when an Indexable / Mapping does not have an index / key."""
350 def __init__(
351 self,
352 message: str = "",
353 node: nodes.NodeNG | bases.Instance | None = None,
354 index: nodes.Subscript | None = None,
355 context: InferenceContext | None = None,
356 **kws: Any,
357 ) -> None:
358 self.node = node
359 self.index = index
360 self.context = context
361 super().__init__(message, **kws)
364class AstroidTypeError(AstroidError):
365 """Raised when a TypeError would be expected in Python code."""
367 def __init__(
368 self,
369 message: str = "",
370 node: nodes.NodeNG | bases.Instance | None = None,
371 index: nodes.Subscript | None = None,
372 context: InferenceContext | None = None,
373 **kws: Any,
374 ) -> None:
375 self.node = node
376 self.index = index
377 self.context = context
378 super().__init__(message, **kws)
381class AstroidValueError(AstroidError):
382 """Raised when a ValueError would be expected in Python code."""
385class InferenceOverwriteError(AstroidError):
386 """Raised when an inference tip is overwritten.
388 Currently only used for debugging.
389 """
392class ParentMissingError(AstroidError):
393 """Raised when a node which is expected to have a parent attribute is missing one.
395 Standard attributes:
396 target: The node for which the parent lookup failed.
397 """
399 def __init__(self, target: nodes.NodeNG) -> None:
400 self.target = target
401 super().__init__(message=f"Parent not found on {target!r}.")
404class StatementMissing(ParentMissingError):
405 """Raised when a call to node.statement() does not return a node.
407 This is because a node in the chain does not have a parent attribute
408 and therefore does not return a node for statement().
410 Standard attributes:
411 target: The node for which the parent lookup failed.
412 """
414 def __init__(self, target: nodes.NodeNG) -> None:
415 super(ParentMissingError, self).__init__(
416 message=f"Statement not found on {target!r}"
417 )
420SuperArgumentTypeError = SuperError
421UnresolvableName = NameInferenceError
422NotFoundError = AttributeInferenceError