Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/astroid/exceptions.py: 40%

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

126 statements  

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 

5"""This module contains exceptions used in the astroid library.""" 

6 

7from __future__ import annotations 

8 

9from collections.abc import Iterable, Iterator 

10from typing import TYPE_CHECKING, Any 

11 

12from astroid.typing import InferenceResult, SuccessfulInferenceResult 

13 

14if TYPE_CHECKING: 

15 from astroid import arguments, bases, nodes, objects 

16 from astroid.context import InferenceContext 

17 

18__all__ = ( 

19 "AstroidBuildingError", 

20 "AstroidError", 

21 "AstroidImportError", 

22 "AstroidIndexError", 

23 "AstroidSyntaxError", 

24 "AstroidTypeError", 

25 "AstroidValueError", 

26 "AttributeInferenceError", 

27 "DuplicateBasesError", 

28 "InconsistentMroError", 

29 "InferenceError", 

30 "InferenceOverwriteError", 

31 "MroError", 

32 "NameInferenceError", 

33 "NoDefault", 

34 "NotFoundError", 

35 "ParentMissingError", 

36 "ResolveError", 

37 "StatementMissing", 

38 "SuperArgumentTypeError", 

39 "SuperError", 

40 "TooManyLevelsError", 

41 "UnresolvableName", 

42 "UseInferenceDefault", 

43) 

44 

45 

46class AstroidError(Exception): 

47 """Base exception class for all astroid related exceptions. 

48 

49 AstroidError and its subclasses are structured, intended to hold 

50 objects representing state when the exception is thrown. Field 

51 values are passed to the constructor as keyword-only arguments. 

52 Each subclass has its own set of standard fields, but use your 

53 best judgment to decide whether a specific exception instance 

54 needs more or fewer fields for debugging. Field values may be 

55 used to lazily generate the error message: self.message.format() 

56 will be called with the field names and values supplied as keyword 

57 arguments. 

58 """ 

59 

60 def __init__(self, message: str = "", **kws: Any) -> None: 

61 super().__init__(message) 

62 self.message = message 

63 for key, value in kws.items(): 

64 setattr(self, key, value) 

65 

66 def __str__(self) -> str: 

67 try: 

68 return self.message.format(**vars(self)) 

69 except ValueError: 

70 return self.message # Return raw message if formatting fails 

71 

72 

73class AstroidBuildingError(AstroidError): 

74 """Exception class when we are unable to build an astroid representation. 

75 

76 Standard attributes: 

77 modname: Name of the module that AST construction failed for. 

78 error: Exception raised during construction. 

79 """ 

80 

81 def __init__( 

82 self, 

83 message: str = "Failed to import module {modname}.", 

84 modname: str | None = None, 

85 error: Exception | None = None, 

86 source: str | None = None, 

87 path: str | None = None, 

88 cls: type | None = None, 

89 class_repr: str | None = None, 

90 **kws: Any, 

91 ) -> None: 

92 self.modname = modname 

93 self.error = error 

94 self.source = source 

95 self.path = path 

96 self.cls = cls 

97 self.class_repr = class_repr 

98 super().__init__(message, **kws) 

99 

100 

101class AstroidImportError(AstroidBuildingError): 

102 """Exception class used when a module can't be imported by astroid.""" 

103 

104 

105class TooManyLevelsError(AstroidImportError): 

106 """Exception class which is raised when a relative import was beyond the top-level. 

107 

108 Standard attributes: 

109 level: The level which was attempted. 

110 name: the name of the module on which the relative import was attempted. 

111 """ 

112 

113 def __init__( 

114 self, 

115 message: str = "Relative import with too many levels " 

116 "({level}) for module {name!r}", 

117 level: int | None = None, 

118 name: str | None = None, 

119 **kws: Any, 

120 ) -> None: 

121 self.level = level 

122 self.name = name 

123 super().__init__(message, **kws) 

124 

125 

126class AstroidSyntaxError(AstroidBuildingError): 

127 """Exception class used when a module can't be parsed.""" 

128 

129 def __init__( 

130 self, 

131 message: str, 

132 modname: str | None, 

133 error: Exception, 

134 path: str | None, 

135 source: str | None = None, 

136 ) -> None: 

137 super().__init__(message, modname, error, source, path) 

138 

139 

140class NoDefault(AstroidError): 

141 """Raised by function's `default_value` method when an argument has 

142 no default value. 

143 

144 Standard attributes: 

145 func: Function node. 

146 name: Name of argument without a default. 

147 """ 

148 

149 def __init__( 

150 self, 

151 message: str = "{func!r} has no default for {name!r}.", 

152 func: nodes.FunctionDef | None = None, 

153 name: str | None = None, 

154 **kws: Any, 

155 ) -> None: 

156 self.func = func 

157 self.name = name 

158 super().__init__(message, **kws) 

159 

160 

161class ResolveError(AstroidError): 

162 """Base class of astroid resolution/inference error. 

163 

164 ResolveError is not intended to be raised. 

165 

166 Standard attributes: 

167 context: InferenceContext object. 

168 """ 

169 

170 def __init__( 

171 self, message: str = "", context: InferenceContext | None = None, **kws: Any 

172 ) -> None: 

173 self.context = context 

174 super().__init__(message, **kws) 

175 

176 

177class MroError(ResolveError): 

178 """Error raised when there is a problem with method resolution of a class. 

179 

180 Standard attributes: 

181 mros: A sequence of sequences containing ClassDef nodes. 

182 cls: ClassDef node whose MRO resolution failed. 

183 context: InferenceContext object. 

184 """ 

185 

186 def __init__( 

187 self, 

188 message: str, 

189 mros: Iterable[Iterable[nodes.ClassDef]], 

190 cls: nodes.ClassDef, 

191 context: InferenceContext | None = None, 

192 **kws: Any, 

193 ) -> None: 

194 self.mros = mros 

195 self.cls = cls 

196 self.context = context 

197 super().__init__(message, **kws) 

198 

199 def __str__(self) -> str: 

200 mro_names = ", ".join(f"({', '.join(b.name for b in m)})" for m in self.mros) 

201 return self.message.format(mros=mro_names, cls=self.cls) 

202 

203 

204class DuplicateBasesError(MroError): 

205 """Error raised when there are duplicate bases in the same class bases.""" 

206 

207 

208class InconsistentMroError(MroError): 

209 """Error raised when a class's MRO is inconsistent.""" 

210 

211 

212class SuperError(ResolveError): 

213 """Error raised when there is a problem with a *super* call. 

214 

215 Standard attributes: 

216 *super_*: The Super instance that raised the exception. 

217 context: InferenceContext object. 

218 """ 

219 

220 def __init__(self, message: str, super_: objects.Super, **kws: Any) -> None: 

221 self.super_ = super_ 

222 super().__init__(message, **kws) 

223 

224 def __str__(self) -> str: 

225 return self.message.format(**vars(self.super_)) 

226 

227 

228class InferenceError(ResolveError): # pylint: disable=too-many-instance-attributes 

229 """Raised when we are unable to infer a node. 

230 

231 Standard attributes: 

232 node: The node inference was called on. 

233 context: InferenceContext object. 

234 """ 

235 

236 def __init__( # pylint: disable=too-many-arguments, too-many-positional-arguments 

237 self, 

238 message: str = "Inference failed for {node!r}.", 

239 node: InferenceResult | None = None, 

240 context: InferenceContext | None = None, 

241 target: InferenceResult | None = None, 

242 targets: InferenceResult | None = None, 

243 attribute: str | None = None, 

244 unknown: InferenceResult | None = None, 

245 assign_path: list[int] | None = None, 

246 caller: SuccessfulInferenceResult | None = None, 

247 stmts: Iterator[InferenceResult] | None = None, 

248 frame: InferenceResult | None = None, 

249 call_site: arguments.CallSite | None = None, 

250 func: InferenceResult | None = None, 

251 arg: str | None = None, 

252 positional_arguments: list | None = None, 

253 unpacked_args: list | None = None, 

254 keyword_arguments: dict | None = None, 

255 unpacked_kwargs: dict | None = None, 

256 **kws: Any, 

257 ) -> None: 

258 self.node = node 

259 self.context = context 

260 self.target = target 

261 self.targets = targets 

262 self.attribute = attribute 

263 self.unknown = unknown 

264 self.assign_path = assign_path 

265 self.caller = caller 

266 self.stmts = stmts 

267 self.frame = frame 

268 self.call_site = call_site 

269 self.func = func 

270 self.arg = arg 

271 self.positional_arguments = positional_arguments 

272 self.unpacked_args = unpacked_args 

273 self.keyword_arguments = keyword_arguments 

274 self.unpacked_kwargs = unpacked_kwargs 

275 super().__init__(message, **kws) 

276 

277 

278# Why does this inherit from InferenceError rather than ResolveError? 

279# Changing it causes some inference tests to fail. 

280class NameInferenceError(InferenceError): 

281 """Raised when a name lookup fails, corresponds to NameError. 

282 

283 Standard attributes: 

284 name: The name for which lookup failed, as a string. 

285 scope: The node representing the scope in which the lookup occurred. 

286 context: InferenceContext object. 

287 """ 

288 

289 def __init__( 

290 self, 

291 message: str = "{name!r} not found in {scope!r}.", 

292 name: str | None = None, 

293 scope: nodes.LocalsDictNodeNG | None = None, 

294 context: InferenceContext | None = None, 

295 **kws: Any, 

296 ) -> None: 

297 self.name = name 

298 self.scope = scope 

299 self.context = context 

300 super().__init__(message, **kws) 

301 

302 

303class AttributeInferenceError(ResolveError): 

304 """Raised when an attribute lookup fails, corresponds to AttributeError. 

305 

306 Standard attributes: 

307 target: The node for which lookup failed. 

308 attribute: The attribute for which lookup failed, as a string. 

309 context: InferenceContext object. 

310 """ 

311 

312 def __init__( 

313 self, 

314 message: str = "{attribute!r} not found on {target!r}.", 

315 attribute: str = "", 

316 target: nodes.NodeNG | bases.BaseInstance | None = None, 

317 context: InferenceContext | None = None, 

318 mros: list[nodes.ClassDef] | None = None, 

319 super_: nodes.ClassDef | None = None, 

320 cls: nodes.ClassDef | None = None, 

321 **kws: Any, 

322 ) -> None: 

323 self.attribute = attribute 

324 self.target = target 

325 self.context = context 

326 self.mros = mros 

327 self.super_ = super_ 

328 self.cls = cls 

329 super().__init__(message, **kws) 

330 

331 

332class UseInferenceDefault(Exception): 

333 """Exception to be raised in custom inference function to indicate that it 

334 should go back to the default behaviour. 

335 """ 

336 

337 

338class _NonDeducibleTypeHierarchy(Exception): 

339 """Raised when is_subtype / is_supertype can't deduce the relation between two 

340 types. 

341 """ 

342 

343 

344class AstroidIndexError(AstroidError): 

345 """Raised when an Indexable / Mapping does not have an index / key.""" 

346 

347 def __init__( 

348 self, 

349 message: str = "", 

350 node: nodes.NodeNG | bases.Instance | None = None, 

351 index: nodes.Subscript | None = None, 

352 context: InferenceContext | None = None, 

353 **kws: Any, 

354 ) -> None: 

355 self.node = node 

356 self.index = index 

357 self.context = context 

358 super().__init__(message, **kws) 

359 

360 

361class AstroidTypeError(AstroidError): 

362 """Raised when a TypeError would be expected in Python code.""" 

363 

364 def __init__( 

365 self, 

366 message: str = "", 

367 node: nodes.NodeNG | bases.Instance | None = None, 

368 index: nodes.Subscript | None = None, 

369 context: InferenceContext | None = None, 

370 **kws: Any, 

371 ) -> None: 

372 self.node = node 

373 self.index = index 

374 self.context = context 

375 super().__init__(message, **kws) 

376 

377 

378class AstroidValueError(AstroidError): 

379 """Raised when a ValueError would be expected in Python code.""" 

380 

381 

382class InferenceOverwriteError(AstroidError): 

383 """Raised when an inference tip is overwritten. 

384 

385 Currently only used for debugging. 

386 """ 

387 

388 

389class ParentMissingError(AstroidError): 

390 """Raised when a node which is expected to have a parent attribute is missing one. 

391 

392 Standard attributes: 

393 target: The node for which the parent lookup failed. 

394 """ 

395 

396 def __init__(self, target: nodes.NodeNG) -> None: 

397 self.target = target 

398 super().__init__(message=f"Parent not found on {target!r}.") 

399 

400 

401class StatementMissing(ParentMissingError): 

402 """Raised when a call to node.statement() does not return a node. 

403 

404 This is because a node in the chain does not have a parent attribute 

405 and therefore does not return a node for statement(). 

406 

407 Standard attributes: 

408 target: The node for which the parent lookup failed. 

409 """ 

410 

411 def __init__(self, target: nodes.NodeNG) -> None: 

412 super(ParentMissingError, self).__init__( 

413 message=f"Statement not found on {target!r}" 

414 ) 

415 

416 

417SuperArgumentTypeError = SuperError 

418UnresolvableName = NameInferenceError 

419NotFoundError = AttributeInferenceError