Debian Codegraph @

friendly_traceback/core.py

raw symbols SCIP
1 """core.py
2
3 The exception hook at the heart of Friendly.
4
5 You should not need to use any of the functions defined here;
6 they are considered to be internal functions, subject to change at any
7 time. If functions defined in friendly_traceback.__init__.py do not meet your needs,
8 please file an issue.
9 """
10
11 import re
12 import traceback
13 import types
14 from typing import List, Optional, Type
15
16 from . import debug_helper, info_generic, info_variables, message_parser, tb_data
17 from .frame_info import FrameInfo
18 from .ft_gettext import current_lang
19 from .path_info import path_utils
20 from .source_cache import cache
21 from .syntax_errors import analyze_syntax, indentation_error
22 from .typing_info import _E, Info
23
24 try:
25 import executing # noqa
26 except ImportError: # pragma: no cover
27 pass # ignore errors when processed by Sphinx
28
29 TracebackData = tb_data.TracebackData
30
31 _ = current_lang.translate
32
33 # ====================
34 # The following is an example of a formatted traceback, with
35 # some parts identified with (partial) names used below
36 #
37 # Python exception: [header]
38
39 # [message]
40 # UnboundLocalError: local variable 'a' referenced before assignment
41
42 # [generic]
43 # In Python, variables that are used inside a function are known as
44 # local variables. Before they are used, they must be assigned a value.
45 # A variable that is used before it is assigned a value is assumed to
46 # be defined outside that function; it is known as a 'global'
47 # (or sometimes 'nonlocal') variable. You cannot assign a value to such
48 # a global variable inside a function without first indicating to
49 # Python that this is a global variable, otherwise you will see
50 # an UnboundLocalError.
51
52 # [cause_header and cause]
53 # Likely cause:
54 # The variable that appears to cause the problem is 'abc'.
55 # Try inserting the statement
56 # global abc
57 # as the first line inside your function.
58 #
59
60 # [last_call_ ...]
61 # Execution stopped on line 14 of file 'C:\Users...\test_unbound_local_error.py'.
62 # 12:
63 # 13: try:
64 # -->14: inner()
65 #
66 # inner: <function test_unbound_local_error.<location... >
67
68 # [exception_raised_ ...]
69 # Exception raised on line 11 of file 'C:\Users\...\test_unbound_local_error.py'.
70 # 9: def inner():
71 # 10: b = 2
72 # -->11: a = a + b
73 #
74 # [6]
75 # b: 2
76
77
78 class FriendlyTraceback:
79 """Main class for creating a friendly traceback.
80
81 All the information available to the end user is stored in a
82 dict called "info". The various keys of that dict are documented
83 in the docstrings of the relevant methods.
84
85 To get all possible attributes set up, one needs to call
86 compile_info() after initializing this class. This is done
87 to allow third-party users to selectively call only one of
88
89 * assign_cause()
90 * assign_generic()
91 * assign_location()
92
93 if they so wish.
94
95 Various functions are available when using a friendly console,
96 which can show part of the information compile here.
97 Among those:
98
99 * where() shows the result of assign_location()
100 * why() shows the cause, as compiled by assign_cause()
101 * hint() is a shorter version of why(), sometimes available.
102 * what() shows the information compiled by assign_generic()
103 """
104
105 info: Info
106
107 def __init__(self, etype: Type[_E], value: _E, tb: types.TracebackType) -> None:
108 """The basic argument are those generated after a traceback
109 and obtained via::
110
111 etype, value, tb = sys.exc_info()
112
113 The "header" key for the info dict is assigned here."""
114 from .config import session
115
116 try:
117 self.tb_data = tb_data.TracebackData(etype, value, tb)
118 except Exception as e: # pragma: no cover
119 debug_helper.log("Uncaught exception in TracebackData:")
120 if debug_helper.DEBUG:
121 raise
122 debug_helper.handle_internal_error(str(e))
123 raise SystemExit
124 self.tb = tb
125 self.suppressed = [" ... " + _("More lines not shown.") + " ..."]
126 self.info = {
127 "header": _("Python exception:"), # Used by HackInScience
128 "lang": session.lang,
129 }
130 self.message = self.assign_message(etype, value) # language independent
131 self.assign_tracebacks()
132 # include the value for debugging purpose in an interactive session ...
133 self.tb_data.exception_instance = value
134 # ... and for extracting the notes information
135 self.add_exception_note()
136
137 def assign_message(self, etype, value) -> str:
138 """Assigns the error message, as the attribute ``message``
139 which is something like::
140
141 NameError: name 'a' is not defined
142 """
143 exc_name = etype.__name__
144 message = value.msg if hasattr(value, "msg") else self.tb_data.full_message
145 self.info["message"] = f"{exc_name}: {message}\n"
146 return self.info["message"]
147
148 def compile_info(self) -> None:
149 """Compile all info that was not set in __init__."""
150 self.assign_generic()
151 # For SyntaxError, assigning the cause may result in better location
152 # information; so we need to do this first.
153 self.assign_cause()
154 self.assign_location()
155 # removing null values; mypy cannot figure out the type correctly here
156 to_remove = [key for key in self.info if not self.info[key]] # type: ignore
157 for key in to_remove:
158 del self.info[key]
159
160 def recompile_info(self) -> None:
161 """This is useful if we need to redisplay some information in a
162 different language than what was originally used.
163 """
164 from .config import session
165
166 self.info["header"] = _("Python exception:")
167 self.info["lang"] = session.lang
168 self.add_exception_note()
169 self.assign_tracebacks()
170 self.compile_info()
171
172 def add_exception_note(self):
173 """Adding information from exception notes; new to Python 3.11"""
174 if not hasattr(self.tb_data.exception_instance, "__notes__"):
175 return
176 notes = self.tb_data.exception_instance.__notes__
177 if len(notes) == 0:
178 return
179 if len(notes) == 1:
180 self.info["exception_notes_intro"] = _(
181 "The exception includes the following note:\n"
182 )
183 else:
184 self.info["exception_notes_intro"] = _(
185 "The exception includes the following notes:\n"
186 )
187 self.info["exception_notes"] = notes
188
189 def assign_cause(self) -> None:
190 """Determine the cause of an exception, which is what is returned
191 by ``why()``.
192 """
193 try:
194 if self.tb_data.filename == "<unknown>" or (
195 self.tb_data.filename == "<string>"
196 and self.tb_data.value.lineno != 1
197 and not issubclass(self.tb_data.exception_type, SyntaxError)
198 ):
199 return
200 except Exception:
201 return
202
203 if tb_data.STR_FAILED in self.message:
204 self.info["cause"] = _(
205 "Warning: improperly formed exception.\n"
206 "I suspect that a custom exception has been raised\n"
207 "with a non-string value used as a message.\n"
208 "This can occur if a `__repr__` or a `__str__` method\n"
209 "raises an exception or does not return a string.\n"
210 )
211 elif issubclass(self.tb_data.exception_type, SyntaxError):
212 self.set_cause_syntax()
213 else:
214 self.set_cause_runtime()
215
216 def set_cause_runtime(self) -> None:
217 """For exceptions other than SyntaxError and subclasses.
218 Sets the value of the following attributes:
219
220 * cause_header
221 * cause
222
223 and possibly:
224
225 * suggest
226
227 the latter being the "hint" appended to the friendly traceback.
228 """
229 etype = self.tb_data.exception_type
230 message = self.tb_data.message
231
232 cause = message_parser.get_likely_cause(etype, message, self.tb_data) # [3]
233 self.info.update(**cause)
234
235 def set_cause_syntax(self) -> None:
236 """For SyntaxError and subclasses. Sets the value of the following
237 attributes:
238
239 * cause_header
240 * cause
241
242 and possibly:
243
244 * suggest
245
246 the latter being the "hint" appended to the friendly traceback.
247 """
248 etype = self.tb_data.exception_type
249 value = self.tb_data.value
250
251 if self.tb_data.filename == "<unknown>":
252 return
253
254 if "encoding problem" in str(self.tb_data.value):
255 self.info["cause"] = _("The encoding of the file was not valid.\n")
256 return
257
258 if etype.__name__ == "IndentationError":
259 self.info["cause"] = indentation_error.set_cause_indentation_error(
260 value, self.tb_data.statement
261 )
262 return
263
264 if etype.__name__ == "TabError":
265 return
266
267 cause = analyze_syntax.set_cause_syntax(value, self.tb_data)
268 self.info.update(**cause)
269
270 def assign_generic(self) -> None:
271 """Assigns the generic information about a given error. This is
272 the answer to ``what()`` as in "What is a NameError?"
273
274 Sets the value of the following attribute:
275
276 * generic
277 """
278 self.info["generic"] = info_generic.get_generic_explanation(
279 self.tb_data.exception_type
280 )
281
282 def assign_location(self) -> None:
283 """This sets the values of the answers to 'where()', that is
284 the information about the location of the exception.
285
286 To determine which attributes will be set, consult the docstring
287 of the following methods.
288
289 For SyntaxError and subclasses: self.locate_parsing_error()
290
291 For other types of exceptions, self.locate_exception_raised(),
292 and possibly self.locate_last_call().
293 """
294 if issubclass(self.tb_data.exception_type, SyntaxError):
295 self.locate_parsing_error()
296 return
297
298 records = self.tb_data.records
299 if not records: # pragma: no cover
300 if issubclass(self.tb_data.exception_type, MemoryError):
301 return
302 debug_helper.log("No record in assign_location().")
303 return
304
305 self.locate_exception_raised(records[-1])
306 if len(records) < 2:
307 return
308
309 self.info["detailed_tb"] = self.get_detailed_stack_info()
310 _ignore, partial_source, var_info = self.info["detailed_tb"][0]
311 self.locate_last_call(records[0], partial_source, var_info)
312
313 def locate_exception_raised(self, record: FrameInfo) -> None:
314 """Sets the values of the following attributes which are
315 part of a friendly
316
317 * exception_raised_header
318 * exception_raised_source
319 * exception_raised_variables
320 """
321 from .config import session
322
323 if self.tb_data.filename == "<stdin>":
324 self.info["exception_raised_source"] = cannot_analyze_stdin()
325 self.info["exception_raised_header"] = ""
326 return
327
328 source = record.partial_source_with_node_range
329 if source.strip() == "0:":
330 source = ""
331 filename = path_utils.shorten_path(record.filename)
332
333 unavailable = filename in ["<unknown>", "<string>"]
334 if unavailable:
335 self.info["exception_raised_source"] = _(
336 "{filename} is not a regular Python file whose contents can be analyzed.\n"
337 ).format(filename=filename)
338 if filename == "<string>":
339 self.info["exception_raised_source"] += _(
340 "If you used `exec`, consider using `friendly_exec` instead.\n"
341 )
342
343 if session.ipython_prompt and filename.startswith("["):
344 self.info["exception_raised_header"] = _(
345 "Exception raised on line `{linenumber}` of code block {filename}.\n"
346 ).format(linenumber=record.lineno, filename=filename)
347 else:
348 self.info["exception_raised_header"] = _(
349 "Exception raised on line `{linenumber}` of file '{filename}'.\n"
350 ).format(linenumber=record.lineno, filename=filename)
351
352 if unavailable:
353 return
354
355 if source.strip() == "<NO SOURCE>":
356 source = _(
357 "{filename} is not a regular Python file whose contents can be analyzed.\n"
358 ).format(filename=filename)
359
360 self.info["exception_raised_source"] = source
361
362 if self.tb_data.node_text:
363 line = self.tb_data.node_text
364 else: # This almost never happens
365 line = record.problem_line()
366
367 var_info = info_variables.get_var_info(line, record.frame)
368 self.info["exception_raised_variables"] = var_info["var_info"]
369 if "additional_variable_warning" in var_info:
370 self.info["additional_variable_warning"] = var_info[
371 "additional_variable_warning"
372 ]
373
374 def locate_last_call(self, record: FrameInfo, partial_source, var_info) -> None:
375 """Sets the values of the following attributes:
376
377 * last_call_header
378 * exception_raised_source
379 * last_call_variables
380 """
381 filename = path_utils.shorten_path(record.filename)
382
383 if filename and "[" in filename:
384 self.info["last_call_header"] = _(
385 "Execution stopped on line `{linenumber}` of code block {filename}.\n"
386 ).format(linenumber=record.lineno, filename=filename)
387 else:
388 self.info["last_call_header"] = _(
389 "Execution stopped on line `{linenumber}` of file '{filename}'.\n"
390 ).format(linenumber=record.lineno, filename=filename)
391 self.info["last_call_source"] = partial_source
392
393 if var_info:
394 self.info["last_call_variables"] = var_info
395
396 def get_detailed_stack_info(self):
397 # sourcery skip: use-named-expression
398 if self.tb_data.filename == "<stdin>":
399 return []
400
401 detailed_tb = []
402 for record in self.tb_data.records:
403 filename = path_utils.shorten_path(record.filename)
404 lineno = record.lineno
405 if record.node_info:
406 _node, _ignore, line = record.node_info
407 else:
408 line = record.problem_line()
409 partial_source = record.partial_source_with_node_range
410 var_info = info_variables.get_var_info(line, record.frame)
411 if "[" in filename:
412 location = _("Code block {filename}, line `{line}`").format(
413 filename=filename, line=lineno
414 )
415 else:
416 location = _("File '{filename}', line `{line}`").format(
417 filename=filename, line=lineno
418 )
419 detailed_tb.append((location, partial_source, var_info["var_info"]))
420 return detailed_tb
421
422 def locate_parsing_error(self) -> None:
423 """Sets the values of the attributes:
424
425 * parsing_error
426 * parsing_source_error
427 """
428 value = self.tb_data.value
429 filepath = value.filename
430 not_regular_file = _(
431 "The entire content of `{filename}` is not available.\n"
432 ).format(filename=filepath)
433 if filepath == "<unknown>":
434 self.info["parsing_error"] = not_regular_file
435 return
436
437 statement = self.tb_data.statement
438 statement.format_statement()
439 partial_source = statement.formatted_partial_source
440
441 short_filename = path_utils.shorten_path(filepath)
442
443 if short_filename and "[" in short_filename:
444 could_not_understand = _(
445 "Python could not understand the code in the code block {filename}\n"
446 ).format(filename=short_filename)
447 else:
448 could_not_understand = _(
449 "Python could not understand the code in the file\n'{filename}'\n"
450 ).format(filename=short_filename)
451
452 if " ^" in partial_source:
453 self.info["parsing_error"] = could_not_understand + _(
454 "at the location indicated.\n"
455 ).format(filename=short_filename)
456 if filepath in ["<string>", "<stdin>"] and self.tb_data.value.lineno != 1:
457 self.info["parsing_error"] += not_regular_file
458 elif filepath: # could be None
459 self.info["parsing_error"] = could_not_understand + "\n"
460
461 self.info["parsing_error_source"] = f"{partial_source}\n"
462
463 def assign_tracebacks(self) -> None:
464 """When required, a standard Python traceback might be required to be
465 included as part of the information shown to the user.
466 This function does the required formatting.
467
468 This function defines 3 traceback:
469 1. The standard Python traceback, given by Python
470 2. A "simulated" Python traceback, which is essentially the same as
471 the one given by Python, except that it excludes modules from this
472 project. In addition, for RecursionError, this traceback is often
473 further shortened, compared with a normal Python traceback.
474 3. A potentially shortened traceback, which does not include too much
475 output so as not to overwhelm beginners. It also includes information
476 about the code on any line mentioned.
477
478 These are given by the attributes:
479
480 * original_python_traceback
481 * simulated_python_traceback
482 * shortened_traceback
483 """
484 from .config import session
485
486 if not hasattr(self, "message"):
487 self.assign_message(self.tb_data.exception_type, self.tb_data.value)
488 if isinstance(self.tb_data.formatted_tb, str):
489 # for example: "Traceback not available from IDLE" ...
490 tb = self.info["message"]
491 if self.tb_data.formatted_tb:
492 tb = self.info["message"] + "\n" + self.tb_data.formatted_tb + "\n"
493 self.info["simulated_python_traceback"] = tb
494 self.info["shortened_traceback"] = tb
495 self.info["original_python_traceback"] = tb
496 return
497
498 # full_tb includes code from friendly-traceback itself
499 full_tb = [line.rstrip() for line in self.tb_data.formatted_tb]
500 python_tb = self.create_traceback(self.tb_data.python_records)
501 tb = self.create_traceback(self.tb_data.records)
502 shortened_tb = self.shorten(tb)
503
504 header = "Traceback (most recent call last):" # not included in records
505 if full_tb[0].startswith(header) and self.tb_data.filename is not None:
506 if not issubclass(self.tb_data.exception_type, SyntaxError):
507 shortened_tb.insert(0, header)
508 python_tb.insert(0, header)
509 else:
510 # The special "Traceback ..." header is not normally shown when
511 # a SyntaxError occurs at an interactive prompt.
512 # In this case, the filename will normally be of the form "<...>"
513 # or we will have changed "File" to be "Code block"
514 for line in shortened_tb:
515 if line.startswith(" File") and "<" not in line:
516 # We have a true file in the traceback
517 shortened_tb.insert(0, header)
518 python_tb.insert(0, header)
519 break
520
521 if "RecursionError" in full_tb[-1]:
522 if len(shortened_tb) > 12:
523 shortened_tb = shortened_tb[:5] + self.suppressed + shortened_tb[-5:]
524 if len(python_tb) > 12:
525 python_tb = python_tb[:5] + self.suppressed + python_tb[-5:]
526
527 exc = self.tb_data.value
528 chain_info = ""
529 short_chain_info = ""
530 if exc.__cause__ or exc.__context__:
531 chain_info = process_exception_chain(self.tb_data.exception_type, exc)
532 parts = chain_info.split("\n\n")
533 # suppress line
534 temp = []
535 for part in parts:
536 part = "\n".join(self.shorten(part.split("\n")))
537 temp.append(part)
538 short_chain_info = "\n\n".join(temp)
539
540 self.info["simulated_python_traceback"] = (
541 chain_info + "\n".join(python_tb) + "\n"
542 )
543 self.info["original_python_traceback"] = chain_info + "\n".join(full_tb) + "\n"
544 # The following is needed for some determining the cause in at
545 # least one case.
546 # skipcq: PYL-W0201
547 self.tb_data.simulated_python_traceback = "\n".join(python_tb) + "\n"
548
549 if session.include_chained_exception:
550 self.info["shortened_traceback"] = (
551 short_chain_info + "\n".join(shortened_tb) + "\n"
552 )
553 else:
554 self.info["shortened_traceback"] = "\n".join(shortened_tb) + "\n"
555
556 def shorten(self, tb: List[str]) -> List[str]:
557 """Shortens a traceback (as list of lines)
558 by removing lines if it exceeds a certain length
559 and by using short synonyms for some common directories."""
560 from .config import session
561
562 shortened_tb = tb[:2] + self.suppressed + tb[-5:] if len(tb) > 12 else tb[:]
563 pattern = re.compile(r'^ File "(.*)", ') # noqa
564 temp = []
565 for line in shortened_tb:
566 match = re.search(pattern, line)
567 if match:
568 filename = match[1]
569 short_filename = path_utils.shorten_path(filename)
570 line = line.replace(filename, short_filename)
571 if (
572 session.ipython_prompt
573 and short_filename[0] == "["
574 and short_filename[-1] == "]"
575 ):
576 line = line.replace(" File", " Code block")
577 line = line.replace('"[', "[").replace(']"', "]")
578 parts = line.split(",")
579 line = ",".join(parts[:2])
580 temp.append(line)
581 return temp
582
583 def create_traceback(self, records: List[FrameInfo]) -> List[str]:
584 """Using records that exclude code from certain files,
585 creates a list from which a standard-looking traceback can
586 be created.
587 """
588 result = []
589 for record in records:
590 result.append(
591 f' File "{record.filename}", line {record.lineno}, in {record.code.co_name}'
592 )
593 bad_line = record.problem_line()
594 result.append(f" {bad_line.strip()}")
595
596 if issubclass(self.tb_data.exception_type, SyntaxError):
597 value = self.tb_data.value
598 offset = value.offset
599 filename = value.filename
600 lines = cache.get_source_lines(filename)
601 result.append(f' File "{filename}", line {value.lineno}')
602 _line = value.text
603 if _line is None:
604 try:
605 _line = lines[value.lineno - 1]
606 except Exception: # noqa
607 pass
608 if _line is not None:
609 if filename == "<fstring>" and lines == ["\n"]:
610 # Before Python 3.9, the traceback included a fake
611 # file for f-strings which only included parts of
612 # the f-string content.
613 cache.add(filename, _line)
614 _line = _line.rstrip()
615 bad_line = _line.strip()
616 if bad_line:
617 # Note end_lineno and end_offset are new in Python 3.10
618 # However, we ensured prior to reaching this point that
619 # they would be defined for other Python versions
620 if (
621 value.end_lineno is not None
622 and value.end_lineno != value.lineno
623 ):
624 nb_carets = len(bad_line) - offset + 1
625 continuation = "-->"
626 else:
627 nb_carets = value.end_offset - offset if value.end_offset else 1
628 continuation = ""
629 nb_carets = max(nb_carets, 1)
630 offset = offset - (len(_line) - len(bad_line)) # removing indent
631 # In some IndentationError cases, and possibly others,
632 # Python's computed offset would show the ^ just before the first token
633 if offset < 1:
634 offset = 1
635 nb_carets = 1
636 continuation = ""
637 result.append(f" {bad_line}")
638 result.append(" " * (3 + offset) + "^" * nb_carets + continuation)
639 result.append(self.info["message"].strip())
640 return result
641
642
643 def process_exception_chain(etype: Type[_E], value: _E) -> str:
644 """Obtains info about exceptions raised while treating other exceptions."""
645 seen = set()
646 lines = []
647
648 direct_cause = (
649 "The above exception was the direct cause of the following exception:"
650 )
651 another_exception = (
652 "During handling of the above exception, another exception occurred:"
653 )
654
655 def chain_exc(typ: Type[_E], exc: _E, tb: Optional[types.TracebackType]) -> None:
656 """Recursive function that insert the contents of 'lines' above."""
657 seen.add(id(exc))
658 context = exc.__context__
659 cause = exc.__cause__
660 if cause is not None and id(cause) not in seen:
661 chain_exc(type(cause), cause, cause.__traceback__)
662 lines.append(f"\n {direct_cause}\n\n")
663 elif (
664 context is not None
665 and not exc.__suppress_context__
666 and id(context) not in seen
667 ):
668 chain_exc(type(context), context, context.__traceback__)
669 lines.append(f"\n {another_exception}\n\n")
670 if tb:
671 tbe = traceback.extract_tb(tb)
672 lines.append("Traceback (most recent call last):\n")
673 for line in traceback.format_list(tbe):
674 lines.append(line)
675 for line in traceback.format_exception_only(typ, exc):
676 lines.append(line)
677
678 chain_exc(etype, value, None)
679 return "".join(lines)
680
681
682 def cannot_analyze_stdin() -> str: # pragma: no cover
683 """Typical case: friendly is imported in an ordinary Python
684 interpreter (REPL), and the user does not activate the friendly
685 console.
686 """
687 from .config import session
688
689 message = _(
690 "Unfortunately, no additional information is available:\n"
691 "the content of file '<stdin>' is not accessible.\n"
692 )
693 if session.suggest_console:
694 print(session.suggest_console)
695 session.suggest_console = ""
696 return message