Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/astroid/exceptions.py: 83%
127 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:53 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:53 +0000
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 Iterator
10from typing import TYPE_CHECKING, Any
12from astroid import util
13from astroid.typing import InferenceResult, SuccessfulInferenceResult
15if TYPE_CHECKING:
16 from astroid import arguments, bases, nodes, objects
17 from astroid.context import InferenceContext
19__all__ = (
20 "AstroidBuildingError",
21 "AstroidBuildingException",
22 "AstroidError",
23 "AstroidImportError",
24 "AstroidIndexError",
25 "AstroidSyntaxError",
26 "AstroidTypeError",
27 "AstroidValueError",
28 "AttributeInferenceError",
29 "BinaryOperationError",
30 "DuplicateBasesError",
31 "InconsistentMroError",
32 "InferenceError",
33 "InferenceOverwriteError",
34 "MroError",
35 "NameInferenceError",
36 "NoDefault",
37 "NotFoundError",
38 "OperationError",
39 "ParentMissingError",
40 "ResolveError",
41 "StatementMissing",
42 "SuperArgumentTypeError",
43 "SuperError",
44 "TooManyLevelsError",
45 "UnaryOperationError",
46 "UnresolvableName",
47 "UseInferenceDefault",
48)
51class AstroidError(Exception):
52 """Base exception class for all astroid related exceptions.
54 AstroidError and its subclasses are structured, intended to hold
55 objects representing state when the exception is thrown. Field
56 values are passed to the constructor as keyword-only arguments.
57 Each subclass has its own set of standard fields, but use your
58 best judgment to decide whether a specific exception instance
59 needs more or fewer fields for debugging. Field values may be
60 used to lazily generate the error message: self.message.format()
61 will be called with the field names and values supplied as keyword
62 arguments.
63 """
65 def __init__(self, message: str = "", **kws: Any) -> None:
66 super().__init__(message)
67 self.message = message
68 for key, value in kws.items():
69 setattr(self, key, value)
71 def __str__(self) -> str:
72 return self.message.format(**vars(self))
75class AstroidBuildingError(AstroidError):
76 """Exception class when we are unable to build an astroid representation.
78 Standard attributes:
79 modname: Name of the module that AST construction failed for.
80 error: Exception raised during construction.
81 """
83 def __init__(
84 self,
85 message: str = "Failed to import module {modname}.",
86 modname: str | None = None,
87 error: Exception | None = None,
88 source: str | None = None,
89 path: str | None = None,
90 cls: type | None = None,
91 class_repr: str | None = None,
92 **kws: Any,
93 ) -> None:
94 self.modname = modname
95 self.error = error
96 self.source = source
97 self.path = path
98 self.cls = cls
99 self.class_repr = class_repr
100 super().__init__(message, **kws)
103class AstroidImportError(AstroidBuildingError):
104 """Exception class used when a module can't be imported by astroid."""
107class TooManyLevelsError(AstroidImportError):
108 """Exception class which is raised when a relative import was beyond the top-level.
110 Standard attributes:
111 level: The level which was attempted.
112 name: the name of the module on which the relative import was attempted.
113 """
115 def __init__(
116 self,
117 message: str = "Relative import with too many levels "
118 "({level}) for module {name!r}",
119 level: int | None = None,
120 name: str | None = None,
121 **kws: Any,
122 ) -> None:
123 self.level = level
124 self.name = name
125 super().__init__(message, **kws)
128class AstroidSyntaxError(AstroidBuildingError):
129 """Exception class used when a module can't be parsed."""
131 def __init__(
132 self,
133 message: str,
134 modname: str | None,
135 error: Exception,
136 path: str | None,
137 source: str | None = None,
138 ) -> None:
139 super().__init__(message, modname, error, source, path)
142class NoDefault(AstroidError):
143 """Raised by function's `default_value` method when an argument has
144 no default value.
146 Standard attributes:
147 func: Function node.
148 name: Name of argument without a default.
149 """
151 def __init__(
152 self,
153 message: str = "{func!r} has no default for {name!r}.",
154 func: nodes.FunctionDef | None = None,
155 name: str | None = None,
156 **kws: Any,
157 ) -> None:
158 self.func = func
159 self.name = name
160 super().__init__(message, **kws)
163class ResolveError(AstroidError):
164 """Base class of astroid resolution/inference error.
166 ResolveError is not intended to be raised.
168 Standard attributes:
169 context: InferenceContext object.
170 """
172 def __init__(
173 self, message: str = "", context: InferenceContext | None = None, **kws: Any
174 ) -> None:
175 self.context = context
176 super().__init__(message, **kws)
179class MroError(ResolveError):
180 """Error raised when there is a problem with method resolution of a class.
182 Standard attributes:
183 mros: A sequence of sequences containing ClassDef nodes.
184 cls: ClassDef node whose MRO resolution failed.
185 context: InferenceContext object.
186 """
188 def __init__(
189 self,
190 message: str,
191 mros: list[nodes.ClassDef],
192 cls: nodes.ClassDef,
193 context: InferenceContext | None = None,
194 **kws: Any,
195 ) -> None:
196 self.mros = mros
197 self.cls = cls
198 self.context = context
199 super().__init__(message, **kws)
201 def __str__(self) -> str:
202 mro_names = ", ".join(f"({', '.join(b.name for b in m)})" for m in self.mros)
203 return self.message.format(mros=mro_names, cls=self.cls)
206class DuplicateBasesError(MroError):
207 """Error raised when there are duplicate bases in the same class bases."""
210class InconsistentMroError(MroError):
211 """Error raised when a class's MRO is inconsistent."""
214class SuperError(ResolveError):
215 """Error raised when there is a problem with a *super* call.
217 Standard attributes:
218 *super_*: The Super instance that raised the exception.
219 context: InferenceContext object.
220 """
222 def __init__(self, message: str, super_: objects.Super, **kws: Any) -> None:
223 self.super_ = super_
224 super().__init__(message, **kws)
226 def __str__(self) -> str:
227 return self.message.format(**vars(self.super_))
230class InferenceError(ResolveError): # pylint: disable=too-many-instance-attributes
231 """Raised when we are unable to infer a node.
233 Standard attributes:
234 node: The node inference was called on.
235 context: InferenceContext object.
236 """
238 def __init__( # pylint: disable=too-many-arguments
239 self,
240 message: str = "Inference failed for {node!r}.",
241 node: InferenceResult | None = None,
242 context: InferenceContext | None = None,
243 target: InferenceResult | None = None,
244 targets: InferenceResult | None = None,
245 attribute: str | None = None,
246 unknown: InferenceResult | None = None,
247 assign_path: list[int] | None = None,
248 caller: SuccessfulInferenceResult | None = None,
249 stmts: Iterator[InferenceResult] | None = None,
250 frame: InferenceResult | None = None,
251 call_site: arguments.CallSite | None = None,
252 func: InferenceResult | None = None,
253 arg: str | None = None,
254 positional_arguments: list | None = None,
255 unpacked_args: list | None = None,
256 keyword_arguments: dict | None = None,
257 unpacked_kwargs: dict | None = None,
258 **kws: Any,
259 ) -> None:
260 self.node = node
261 self.context = context
262 self.target = target
263 self.targets = targets
264 self.attribute = attribute
265 self.unknown = unknown
266 self.assign_path = assign_path
267 self.caller = caller
268 self.stmts = stmts
269 self.frame = frame
270 self.call_site = call_site
271 self.func = func
272 self.arg = arg
273 self.positional_arguments = positional_arguments
274 self.unpacked_args = unpacked_args
275 self.keyword_arguments = keyword_arguments
276 self.unpacked_kwargs = unpacked_kwargs
277 super().__init__(message, **kws)
280# Why does this inherit from InferenceError rather than ResolveError?
281# Changing it causes some inference tests to fail.
282class NameInferenceError(InferenceError):
283 """Raised when a name lookup fails, corresponds to NameError.
285 Standard attributes:
286 name: The name for which lookup failed, as a string.
287 scope: The node representing the scope in which the lookup occurred.
288 context: InferenceContext object.
289 """
291 def __init__(
292 self,
293 message: str = "{name!r} not found in {scope!r}.",
294 name: str | None = None,
295 scope: nodes.LocalsDictNodeNG | None = None,
296 context: InferenceContext | None = None,
297 **kws: Any,
298 ) -> None:
299 self.name = name
300 self.scope = scope
301 self.context = context
302 super().__init__(message, **kws)
305class AttributeInferenceError(ResolveError):
306 """Raised when an attribute lookup fails, corresponds to AttributeError.
308 Standard attributes:
309 target: The node for which lookup failed.
310 attribute: The attribute for which lookup failed, as a string.
311 context: InferenceContext object.
312 """
314 def __init__(
315 self,
316 message: str = "{attribute!r} not found on {target!r}.",
317 attribute: str = "",
318 target: nodes.NodeNG | bases.BaseInstance | None = None,
319 context: InferenceContext | None = None,
320 mros: list[nodes.ClassDef] | None = None,
321 super_: nodes.ClassDef | None = None,
322 cls: nodes.ClassDef | None = None,
323 **kws: Any,
324 ) -> None:
325 self.attribute = attribute
326 self.target = target
327 self.context = context
328 self.mros = mros
329 self.super_ = super_
330 self.cls = cls
331 super().__init__(message, **kws)
334class UseInferenceDefault(Exception):
335 """Exception to be raised in custom inference function to indicate that it
336 should go back to the default behaviour.
337 """
340class _NonDeducibleTypeHierarchy(Exception):
341 """Raised when is_subtype / is_supertype can't deduce the relation between two
342 types.
343 """
346class AstroidIndexError(AstroidError):
347 """Raised when an Indexable / Mapping does not have an index / key."""
349 def __init__(
350 self,
351 message: str = "",
352 node: nodes.NodeNG | bases.Instance | None = None,
353 index: nodes.Subscript | None = None,
354 context: InferenceContext | None = None,
355 **kws: Any,
356 ) -> None:
357 self.node = node
358 self.index = index
359 self.context = context
360 super().__init__(message, **kws)
363class AstroidTypeError(AstroidError):
364 """Raised when a TypeError would be expected in Python code."""
366 def __init__(
367 self,
368 message: str = "",
369 node: nodes.NodeNG | bases.Instance | None = None,
370 index: nodes.Subscript | None = None,
371 context: InferenceContext | None = None,
372 **kws: Any,
373 ) -> None:
374 self.node = node
375 self.index = index
376 self.context = context
377 super().__init__(message, **kws)
380class AstroidValueError(AstroidError):
381 """Raised when a ValueError would be expected in Python code."""
384class InferenceOverwriteError(AstroidError):
385 """Raised when an inference tip is overwritten.
387 Currently only used for debugging.
388 """
391class ParentMissingError(AstroidError):
392 """Raised when a node which is expected to have a parent attribute is missing one.
394 Standard attributes:
395 target: The node for which the parent lookup failed.
396 """
398 def __init__(self, target: nodes.NodeNG) -> None:
399 self.target = target
400 super().__init__(message=f"Parent not found on {target!r}.")
403class StatementMissing(ParentMissingError):
404 """Raised when a call to node.statement() does not return a node.
406 This is because a node in the chain does not have a parent attribute
407 and therefore does not return a node for statement().
409 Standard attributes:
410 target: The node for which the parent lookup failed.
411 """
413 def __init__(self, target: nodes.NodeNG) -> None:
414 super(ParentMissingError, self).__init__(
415 message=f"Statement not found on {target!r}"
416 )
419# Backwards-compatibility aliases
420OperationError = util.BadOperationMessage
421UnaryOperationError = util.BadUnaryOperationMessage
422BinaryOperationError = util.BadBinaryOperationMessage
424SuperArgumentTypeError = SuperError
425UnresolvableName = NameInferenceError
426NotFoundError = AttributeInferenceError
427AstroidBuildingException = AstroidBuildingError