Debian Codegraph @

friendly_traceback/info_generic.py

raw symbols SCIP
1 """This module contains the necessary class and functions needed to
2 help describing what a given exception or warning means
3 (i.e. the answer to ``why()``)
4 of an exception. Most of the content should be considered to be private.
5
6 It does contain one decorator (``register``)
7 which is intended to be part of the public API, but needs to be
8 imported from this module instead of simply from ``friendly_traceback``.
9 """
10
11 import inspect
12 from typing import Any, Callable, Dict, Type
13
14 from .ft_gettext import current_lang, no_information
15 from .typing_info import GenericExplain
16
17 GENERIC: Dict[Type[BaseException], GenericExplain] = {}
18 SUBCLASS: Dict[Any, Any] = {}
19 _ = current_lang.translate
20
21
22 def get_generic_explanation(exception_type: Type[BaseException]) -> str:
23 """Provides a generic explanation about a particular exception."""
24 if hasattr(exception_type, "__name__"):
25 exception_name = exception_type.__name__
26 else:
27 exception_name = exception_type
28 if exception_type in GENERIC:
29 return GENERIC[exception_type]()
30 else:
31 if not issubclass(exception_type, BaseException):
32 return no_information()
33 parents = inspect.getmro(exception_type)
34 for index, parent in enumerate(parents):
35 if parent in GENERIC:
36 tree = [p.__name__ for p in parents[: index + 1]]
37 break
38 else:
39 tree = [p.__name__ for p in parents]
40
41 for parent in parents:
42 if parent in GENERIC:
43 if parent.__name__.endswith("Warning"):
44 explanation = _(
45 "A warning of type `{name}` is a subclass of `{parent}`.\n"
46 ).format(name=exception_name, parent=parent.__name__)
47 else:
48 explanation = _(
49 "An exception of type `{name}` is a subclass of `{parent}`.\n"
50 ).format(name=exception_name, parent=parent.__name__)
51 nothing_specific = _(
52 "Nothing more specific is known about `{name}`."
53 ).format(name=exception_name)
54 if len(tree) > 2:
55 nothing_specific += "\n" + _(
56 "The inheritance is as follows:\n\n" " {tree}\n"
57 ).format(tree=" -> ".join(tree))
58 return explanation + nothing_specific + "\n\n" + GENERIC[parent]()
59
60 return no_information()
61
62
63 def register(
64 error_class: Type[BaseException],
65 ) -> Callable[[GenericExplain], GenericExplain]:
66 """Decorator used to record as available an explanation for a given exception.
67
68 Args:
69 error_class: an exception class.
70
71 Usage::
72
73 from friendly_traceback.info_generic import register
74
75 @register
76 def describe(SomeErrorOrWarning) -> str:
77 '''`SomeErrorOrWarning` means that ...'''
78 """
79
80 def add_exception(function):
81 if error_class in GENERIC:
82 message = f"A description of `{error_class.__name__}` already exists:\n\n"
83 message += GENERIC[error_class]()
84 raise ValueError(message)
85
86 GENERIC[error_class] = function
87
88 def wrapper():
89 return function()
90
91 return wrapper
92
93 return add_exception
94
95
96 @register(Exception)
97 def _exception() -> str:
98 return _(
99 "Most built-in exceptions defined by Python are derived from `Exception`.\n"
100 "All user-defined exceptions should also be derived from this class.\n"
101 )
102
103
104 @register(BaseException)
105 def base_exception() -> str:
106 return _(
107 "`BaseException` is the base class for all built-in exceptions.\n"
108 "It is not meant to be directly inherited by user-defined classes.\n"
109 )
110
111
112 @register(ArithmeticError)
113 def arithmetic_error() -> str:
114 return _(
115 "`ArithmeticError` is the base class for those built-in exceptions\n"
116 "that are raised for various arithmetic errors.\n"
117 )
118
119
120 @register(AssertionError)
121 def assertion_error() -> str:
122 return _(
123 "In Python, the keyword `assert` is used in statements of the form\n"
124 "`assert condition`, to confirm that `condition` is not `False`,\n"
125 "nor equivalent to `False` such as an empty list, etc.\n\n"
126 "If `condition` is `False` or equivalent, an `AssertionError` is raised.\n"
127 )
128
129
130 @register(AttributeError)
131 def attribute_error() -> str:
132 return _(
133 "An `AttributeError` occurs when the code contains something like\n"
134 " `object.x`\n"
135 "and `x` is not a method or attribute (variable) belonging to `object`.\n"
136 )
137
138
139 @register(EOFError)
140 def eof_error() -> str: # pragma: no cover
141 return _(
142 "An `EOFError` is raised when the `input()` function hits\n"
143 "an end-of-file condition (EOF) without reading any data.\n"
144 )
145
146
147 @register(FileNotFoundError)
148 def file_not_found_error() -> str:
149 return _(
150 "A `FileNotFoundError` exception indicates that you\n"
151 "are trying to open a file that cannot be found by Python.\n"
152 "This could be because you misspelled the name of the file.\n"
153 )
154
155
156 @register(ImportError)
157 def import_error() -> str:
158 return _(
159 "An `ImportError` exception indicates that a certain object could not\n"
160 "be imported from a module or package. Most often, this is\n"
161 "because the name of the object is not spelled correctly.\n"
162 )
163
164
165 @register(IndentationError)
166 def indentation_error() -> str:
167 return _(
168 "An `IndentationError` occurs when a given line of code is\n"
169 "not indented (aligned vertically with other lines) as expected.\n"
170 )
171
172
173 @register(IndexError)
174 def index_error() -> str:
175 return _(
176 "An `IndexError` occurs when you try to get an item from a list,\n"
177 "a tuple, or a similar object (sequence), and use an index which\n"
178 "does not exist; typically, this happens because the index you give\n"
179 "is greater than the length of the sequence.\n"
180 )
181
182
183 @register(KeyError)
184 def key_error() -> str:
185 return _(
186 "A `KeyError` is raised when a value is not found as a\n"
187 "key in a Python dict or in a similar object.\n"
188 )
189
190
191 @register(LookupError)
192 def lookup_error() -> str:
193 return _(
194 "`LookupError` is the base class for the exceptions that are raised\n"
195 "when a key or index used on a mapping or sequence is invalid.\n"
196 "It can also be raised directly by codecs.lookup().\n"
197 )
198
199
200 @register(MemoryError)
201 def memory_error() -> str:
202 return _(
203 "Like the name indicates, a `MemoryError` occurs when Python\n"
204 "runs out of memory. This can happen if you create an object\n"
205 "that is too big, like a list with too many items.\n"
206 )
207
208
209 @register(ModuleNotFoundError)
210 def module_not_found_error() -> str:
211 return _(
212 "A `ModuleNotFoundError` exception indicates that you\n"
213 "are trying to import a module that cannot be found by Python.\n"
214 "This could be because you misspelled the name of the module\n"
215 "or because it is not installed on your computer.\n"
216 )
217
218
219 @register(NameError)
220 def name_error() -> str:
221 return _(
222 "A `NameError` exception indicates that a variable or\n"
223 "function name is not known to Python.\n"
224 "Most often, this is because there is a spelling mistake.\n"
225 "However, sometimes it is because the name is used\n"
226 "before being defined or given a value.\n"
227 )
228
229
230 @register(OSError)
231 def os_error() -> str:
232 return _(
233 "An `OSError` exception is usually raised by the Operating System\n"
234 "to indicate that an operation is not allowed or that\n"
235 "a resource is not available.\n"
236 )
237
238
239 @register(OverflowError)
240 def overflow_error() -> str:
241 return _(
242 "An `OverflowError` is raised when the result of an arithmetic operation\n"
243 "is too large to be handled by the computer's processor.\n"
244 )
245
246
247 @register(RecursionError)
248 def recursion_error() -> str:
249 return _(
250 "A `RecursionError` is raised when a function calls itself,\n"
251 "directly or indirectly, too many times.\n"
252 "It almost always indicates that you made an error in your code\n"
253 "and that your program would never stop.\n"
254 )
255
256
257 @register(RuntimeError)
258 def runtime_error() -> str:
259 return _(
260 "A `RuntimeError` is raised when an error is detected that doesn't fall in any\n"
261 "of the more specific exception types defined by Python.\n"
262 )
263
264
265 @register(StopIteration)
266 def stop_iteration() -> str:
267 return _(
268 "`StopIteration` is raised to indicate that an iterator has no more\n"
269 "item to provide when its `__next__` method is called by\n"
270 "the `next()` builtin function.\n"
271 )
272
273
274 @register(SyntaxError)
275 def syntax_error() -> str:
276 return _("A `SyntaxError` occurs when Python cannot understand your code.\n")
277
278
279 @register(TabError)
280 def tab_error() -> str:
281 return _(
282 "A `TabError` indicates that you have used both spaces\n"
283 "and tab characters to indent your code.\n"
284 "This is not allowed in Python.\n"
285 "Indenting your code means to have block of codes aligned vertically\n"
286 "by inserting either spaces or tab characters at the beginning of lines.\n"
287 "Python's recommendation is to always use spaces to indent your code.\n"
288 )
289
290
291 @register(TypeError)
292 def type_error() -> str:
293 return _(
294 "A `TypeError` is usually caused by trying\n"
295 "to combine two incompatible types of objects,\n"
296 "by calling a function with the wrong type of object,\n"
297 "or by trying to do an operation not allowed on a given type of object.\n"
298 )
299
300
301 @register(ValueError)
302 def value_error() -> str:
303 return _(
304 "A `ValueError` indicates that a function or an operation\n"
305 "received an argument of the right type, but an inappropriate value.\n"
306 )
307
308
309 @register(UnboundLocalError)
310 def unbound_local_error() -> str:
311 return _(
312 "In Python, variables that are used inside a function are known as \n"
313 "local variables. Before they are used, they must be assigned a value.\n"
314 "A variable that is used before it is assigned a value is assumed to\n"
315 "be defined outside that function; it is known as a `global`\n"
316 "(or sometimes `nonlocal`) variable. You cannot assign a value to such\n"
317 "a global variable inside a function without first indicating to\n"
318 "Python that this is a global variable, otherwise you will see\n"
319 "an `UnboundLocalError`.\n"
320 )
321
322
323 @register(ZeroDivisionError)
324 def zero_division_error() -> str:
325 return _(
326 "A `ZeroDivisionError` occurs when you are attempting to divide a value\n"
327 "by zero either directly or by using some other mathematical operation.\n"
328 )
329
330
331 @register(UserWarning)
332 def user_warning() -> str:
333 return _("`UserWarning` is the default class for `warnings.warn()`.\n")
334
335
336 @register(SyntaxWarning)
337 def syntax_warning() -> str:
338 return _(
339 "`SyntaxWarning` often indicates that your code will likely not give the result you expect.\n"
340 )
341
342
343 @register(DeprecationWarning)
344 def deprecation_warning() -> str:
345 return _(
346 "`DeprecationWarning` indicates that some feature will not be available in a future version.\n"
347 )
348
349
350 @register(RuntimeWarning)
351 def runtime_warning() -> str:
352 return _(
353 "`RuntimeWarning` often indicates some not recommended runtime features.\n"
354 )
355
356
357 @register(FutureWarning)
358 def future_warning() -> str:
359 return _(
360 "`FutureWarning` is the base category for features that will likely be deprecated\n"
361 "in future Python versions.\n"
362 )
363
364
365 @register(UnicodeWarning)
366 def unicode_warning() -> str:
367 return _("`UnicodeWarning` is the base category for warnings related to unicode.\n")
368
369
370 @register(BytesWarning)
371 def bytes_warning() -> str:
372 return _(
373 "`BytesWarning` is the base category for warnings related to bytes and bytearray.\n"
374 )
375
376
377 @register(Warning) # Keep this one as the last warning
378 def _warning() -> str:
379 return _("`Warning` is the base class of all warning category classes.\n")
380
381
382 # The following are ignored by default:
383 #
384 # PendingDeprecationWarning
385 # Base category for warnings about features that will be deprecated in the future
386 #
387 # ImportWarning
388 # Base category for warnings triggered during the process of importing a module.
389 #
390 # ResourceWarning
391 # Base category for warnings related to resource usage (ignored by default).