Debian Codegraph @

lib-python/3/traceback.py

raw symbols SCIP
1 """Extract, format and print information about Python stack traces."""
2
3 import collections.abc
4 import itertools
5 import linecache
6 import sys
7 import textwrap
8 from contextlib import suppress
9
10 __all__ = ['extract_stack', 'extract_tb', 'format_exception',
11 'format_exception_only', 'format_list', 'format_stack',
12 'format_tb', 'print_exc', 'format_exc', 'print_exception',
13 'print_last', 'print_stack', 'print_tb', 'clear_frames',
14 'FrameSummary', 'StackSummary', 'TracebackException',
15 'walk_stack', 'walk_tb']
16
17 #
18 # Formatting and printing lists of traceback lines.
19 #
20
21 def print_list(extracted_list, file=None):
22 """Print the list of tuples as returned by extract_tb() or
23 extract_stack() as a formatted stack trace to the given file."""
24 if file is None:
25 file = sys.stderr
26 for item in StackSummary.from_list(extracted_list).format():
27 print(item, file=file, end="")
28
29 def format_list(extracted_list):
30 """Format a list of tuples or FrameSummary objects for printing.
31
32 Given a list of tuples or FrameSummary objects as returned by
33 extract_tb() or extract_stack(), return a list of strings ready
34 for printing.
35
36 Each string in the resulting list corresponds to the item with the
37 same index in the argument list. Each string ends in a newline;
38 the strings may contain internal newlines as well, for those items
39 whose source text line is not None.
40 """
41 return StackSummary.from_list(extracted_list).format()
42
43 #
44 # Printing and Extracting Tracebacks.
45 #
46
47 def print_tb(tb, limit=None, file=None):
48 """Print up to 'limit' stack trace entries from the traceback 'tb'.
49
50 If 'limit' is omitted or None, all entries are printed. If 'file'
51 is omitted or None, the output goes to sys.stderr; otherwise
52 'file' should be an open file or file-like object with a write()
53 method.
54 """
55 print_list(extract_tb(tb, limit=limit), file=file)
56
57 def format_tb(tb, limit=None):
58 """A shorthand for 'format_list(extract_tb(tb, limit))'."""
59 return extract_tb(tb, limit=limit).format()
60
61 def extract_tb(tb, limit=None):
62 """
63 Return a StackSummary object representing a list of
64 pre-processed entries from traceback.
65
66 This is useful for alternate formatting of stack traces. If
67 'limit' is omitted or None, all entries are extracted. A
68 pre-processed stack trace entry is a FrameSummary object
69 containing attributes filename, lineno, name, and line
70 representing the information that is usually printed for a stack
71 trace. The line is a string with leading and trailing
72 whitespace stripped; if the source is not available it is None.
73 """
74 return StackSummary._extract_from_extended_frame_gen(
75 _walk_tb_with_full_positions(tb), limit=limit)
76
77 #
78 # Exception formatting and output.
79 #
80
81 _cause_message = (
82 "\nThe above exception was the direct cause "
83 "of the following exception:\n\n")
84
85 _context_message = (
86 "\nDuring handling of the above exception, "
87 "another exception occurred:\n\n")
88
89
90 class _Sentinel:
91 def __repr__(self):
92 return "<implicit>"
93
94 _sentinel = _Sentinel()
95
96 def _parse_value_tb(exc, value, tb):
97 if (value is _sentinel) != (tb is _sentinel):
98 raise ValueError("Both or neither of value and tb must be given")
99 if value is tb is _sentinel:
100 if exc is not None:
101 if isinstance(exc, BaseException):
102 return exc, exc.__traceback__
103
104 raise TypeError(f'Exception expected for value, '
105 f'{type(exc).__name__} found')
106 else:
107 return None, None
108 return value, tb
109
110
111 def print_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \
112 file=None, chain=True):
113 """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
114
115 This differs from print_tb() in the following ways: (1) if
116 traceback is not None, it prints a header "Traceback (most recent
117 call last):"; (2) it prints the exception type and value after the
118 stack trace; (3) if type is SyntaxError and value has the
119 appropriate format, it prints the line where the syntax error
120 occurred with a caret on the next line indicating the approximate
121 position of the error.
122 """
123 value, tb = _parse_value_tb(exc, value, tb)
124 te = TracebackException(type(value), value, tb, limit=limit, compact=True)
125 te.print(file=file, chain=chain)
126
127 # PyPy change: copy _print_exception_bltin from cpy 3.13
128
129 BUILTIN_EXCEPTION_LIMIT = object()
130
131 def _print_exception_bltin(exc, /):
132 file = sys.stderr if sys.stderr is not None else sys.__stderr__
133 colorize = _colorize.can_colorize()
134 return print_exception(exc, limit=BUILTIN_EXCEPTION_LIMIT, file=file, colorize=colorize)
135
136 # end PyPy change
137
138
139 def format_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \
140 chain=True, colorize=False):
141 """Format a stack trace and the exception information.
142
143 The arguments have the same meaning as the corresponding arguments
144 to print_exception(). The return value is a list of strings, each
145 ending in a newline and some containing internal newlines. When
146 these lines are concatenated and printed, exactly the same text is
147 printed as does print_exception().
148 """
149 value, tb = _parse_value_tb(exc, value, tb)
150 te = TracebackException(type(value), value, tb, limit=limit, compact=True)
151 te._colorize = colorize
152 return list(te.format(chain=chain))
153
154
155 def format_exception_only(exc, /, value=_sentinel, colorize=False):
156 """Format the exception part of a traceback.
157
158 The return value is a list of strings, each ending in a newline.
159
160 The list contains the exception's message, which is
161 normally a single string; however, for :exc:`SyntaxError` exceptions, it
162 contains several lines that (when printed) display detailed information
163 about where the syntax error occurred. Following the message, the list
164 contains the exception's ``__notes__``.
165 """
166 if value is _sentinel:
167 value = exc
168 te = TracebackException(type(value), value, None, compact=True)
169 if colorize:
170 te._colorize = True
171 return list(te.format_exception_only())
172
173
174 # -- not official API but folk probably use these two functions.
175
176 def _format_final_exc_line(etype, value, colorize=False):
177 valuestr = _safe_string(value, 'exception')
178 if colorize:
179 from _colorize import ANSIColors
180 if value is None or not valuestr:
181 line = f"{ANSIColors.BOLD_MAGENTA}{etype}{ANSIColors.RESET}\n"
182 else:
183 line = f"{ANSIColors.BOLD_MAGENTA}{etype}{ANSIColors.RESET}: {ANSIColors.MAGENTA}{valuestr}{ANSIColors.RESET}\n"
184 return line
185 if value is None or not valuestr:
186 line = "%s\n" % etype
187 else:
188 line = "%s: %s\n" % (etype, valuestr)
189 return line
190
191 def _safe_string(value, what, func=str):
192 try:
193 return func(value)
194 except:
195 return f'<{what} {func.__name__}() failed>'
196
197 # --
198
199 def print_exc(limit=None, file=None, chain=True):
200 """Shorthand for 'print_exception(*sys.exc_info(), limit, file)'."""
201 print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain)
202
203 def format_exc(limit=None, chain=True):
204 """Like print_exc() but return a string."""
205 return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain))
206
207 def print_last(limit=None, file=None, chain=True):
208 """This is a shorthand for 'print_exception(sys.last_type,
209 sys.last_value, sys.last_traceback, limit, file)'."""
210 if not hasattr(sys, "last_type"):
211 raise ValueError("no last exception")
212 print_exception(sys.last_type, sys.last_value, sys.last_traceback,
213 limit, file, chain)
214
215 #
216 # Printing and Extracting Stacks.
217 #
218
219 def print_stack(f=None, limit=None, file=None):
220 """Print a stack trace from its invocation point.
221
222 The optional 'f' argument can be used to specify an alternate
223 stack frame at which to start. The optional 'limit' and 'file'
224 arguments have the same meaning as for print_exception().
225 """
226 if f is None:
227 f = sys._getframe().f_back
228 print_list(extract_stack(f, limit=limit), file=file)
229
230
231 def format_stack(f=None, limit=None):
232 """Shorthand for 'format_list(extract_stack(f, limit))'."""
233 if f is None:
234 f = sys._getframe().f_back
235 return format_list(extract_stack(f, limit=limit))
236
237
238 def extract_stack(f=None, limit=None):
239 """Extract the raw traceback from the current stack frame.
240
241 The return value has the same format as for extract_tb(). The
242 optional 'f' and 'limit' arguments have the same meaning as for
243 print_stack(). Each item in the list is a quadruple (filename,
244 line number, function name, text), and the entries are in order
245 from oldest to newest stack frame.
246 """
247 if f is None:
248 f = sys._getframe().f_back
249 stack = StackSummary.extract(walk_stack(f), limit=limit)
250 stack.reverse()
251 return stack
252
253
254 def clear_frames(tb):
255 "Clear all references to local variables in the frames of a traceback."
256 while tb is not None:
257 try:
258 tb.tb_frame.clear()
259 except RuntimeError:
260 # Ignore the exception raised if the frame is still executing.
261 pass
262 tb = tb.tb_next
263
264
265 class FrameSummary:
266 """Information about a single frame from a traceback.
267
268 - :attr:`filename` The filename for the frame.
269 - :attr:`lineno` The line within filename for the frame that was
270 active when the frame was captured.
271 - :attr:`name` The name of the function or method that was executing
272 when the frame was captured.
273 - :attr:`line` The text from the linecache module for the
274 of code that was running when the frame was captured.
275 - :attr:`locals` Either None if locals were not supplied, or a dict
276 mapping the name to the repr() of the variable.
277 """
278
279 __slots__ = ('filename', 'lineno', 'end_lineno', 'colno', 'end_colno',
280 'name', '_line', 'locals')
281
282 def __init__(self, filename, lineno, name, *, lookup_line=True,
283 locals=None, line=None,
284 end_lineno=None, colno=None, end_colno=None):
285 """Construct a FrameSummary.
286
287 :param lookup_line: If True, `linecache` is consulted for the source
288 code line. Otherwise, the line will be looked up when first needed.
289 :param locals: If supplied the frame locals, which will be captured as
290 object representations.
291 :param line: If provided, use this instead of looking up the line in
292 the linecache.
293 """
294 self.filename = filename
295 self.lineno = lineno
296 self.name = name
297 self._line = line
298 if lookup_line:
299 self.line
300 self.locals = {k: repr(v) for k, v in locals.items()} if locals else None
301 self.end_lineno = end_lineno
302 self.colno = colno
303 self.end_colno = end_colno
304
305 def __eq__(self, other):
306 if isinstance(other, FrameSummary):
307 return (self.filename == other.filename and
308 self.lineno == other.lineno and
309 self.name == other.name and
310 self.locals == other.locals)
311 if isinstance(other, tuple):
312 return (self.filename, self.lineno, self.name, self.line) == other
313 return NotImplemented
314
315 def __getitem__(self, pos):
316 return (self.filename, self.lineno, self.name, self.line)[pos]
317
318 def __iter__(self):
319 return iter([self.filename, self.lineno, self.name, self.line])
320
321 def __repr__(self):
322 return "<FrameSummary file {filename}, line {lineno} in {name}>".format(
323 filename=self.filename, lineno=self.lineno, name=self.name)
324
325 def __len__(self):
326 return 4
327
328 @property
329 def _original_line(self):
330 # Returns the line as-is from the source, without modifying whitespace.
331 self.line
332 return self._line
333
334 @property
335 def line(self):
336 if self._line is None:
337 if self.lineno is None:
338 return None
339 self._line = linecache.getline(self.filename, self.lineno)
340 return self._line.strip()
341
342 # PyPy modification: adapt to the changes in extract to use a helper function
343 def walk_stack(f):
344 """Walk a stack yielding the frame and line number for each frame.
345
346 This will follow f.f_back from the given frame. If no frame is given, the
347 current stack is used. Usually used with StackSummary.extract.
348 """
349 if f is None:
350 f = sys._getframe().f_back
351 return _walk_stack(f)
352
353 def _walk_stack(f):
354 while f is not None:
355 yield f, f.f_lineno
356 f = f.f_back
357
358 def _construct_positionful_frame(f, last_i, *args, **kwargs):
359 f_summary = FrameSummary(*args, **kwargs)
360
361 # If we can't retrieve the traceback's last instruction
362 # we will give up here. It normally shouldn't happen but
363 # just handling the error path.
364 if last_i is not None:
365 # last_i represents the offset in terms of bytes, so for normalizing it
366 # for a list of instructions we need to divide it by 2.
367 instr_index = last_i // 2
368 positions = f.f_code.co_positions()
369 if len(positions) > instr_index:
370 _, f_summary.end_lineno, f_summary.colno, f_summary.end_colno = positions[instr_index]
371
372 return f_summary
373
374 def _filelink(filename):
375 if filename.startswith("<") and filename.endswith(">"):
376 return filename
377 url = f"file://{filename}"
378 # OSC 8 ; params ; URI ST <name> OSC 8 ;; ST
379 return f'\x1b]8;;{url}\x1b\\{filename}\x1b]8;;\x1b\\'
380
381 # end PyPy modification
382
383
384 def walk_tb(tb):
385 """Walk a traceback yielding the frame and line number for each frame.
386
387 This will follow tb.tb_next (and thus is in the opposite order to
388 walk_stack). Usually used with StackSummary.extract.
389 """
390 while tb is not None:
391 yield tb.tb_frame, tb.tb_lineno
392 tb = tb.tb_next
393
394 def _walk_tb_with_full_positions(tb):
395 # Internal version of walk_tb that yields full code positions including
396 # end line and column information.
397 while tb is not None:
398 positions = _get_code_position(tb.tb_frame.f_code, tb.tb_lasti)
399 # Yield tb_lineno when co_positions does not have a line number to
400 # maintain behavior with walk_tb.
401 if positions[0] is None:
402 yield tb.tb_frame, (tb.tb_lineno, ) + positions[1:]
403 else:
404 yield tb.tb_frame, positions
405 tb = tb.tb_next
406
407
408 def _get_code_position(code, instruction_index):
409 if instruction_index < 0:
410 return (None, None, None, None)
411 positions_gen = code.co_positions()
412 return next(itertools.islice(positions_gen, instruction_index // 2, None))
413
414
415 _RECURSIVE_CUTOFF = 3 # Also hardcoded in traceback.c.
416
417 class StackSummary(list):
418 """A list of FrameSummary objects, representing a stack of frames."""
419
420 @classmethod
421 def extract(klass, frame_gen, *, limit=None, lookup_lines=True,
422 capture_locals=False):
423 """Create a StackSummary from a traceback or stack object.
424
425 :param frame_gen: A generator that yields (frame, lineno) tuples
426 whose summaries are to be included in the stack.
427 :param limit: None to include all frames or the number of frames to
428 include.
429 :param lookup_lines: If True, lookup lines for each frame immediately,
430 otherwise lookup is deferred until the frame is rendered.
431 :param capture_locals: If True, the local variables from each frame will
432 be captured as object representations into the FrameSummary.
433 """
434 def extended_frame_gen():
435 for f, lineno in frame_gen:
436 yield f, (lineno, None, None, None)
437
438 return klass._extract_from_extended_frame_gen(
439 extended_frame_gen(), limit=limit, lookup_lines=lookup_lines,
440 capture_locals=capture_locals)
441
442 @classmethod
443 def _extract_from_extended_frame_gen(klass, frame_gen, *, limit=None,
444 lookup_lines=True, capture_locals=False):
445 # Same as extract but operates on a frame generator that yields
446 # (frame, (lineno, end_lineno, colno, end_colno)) in the stack.
447 # Only lineno is required, the remaining fields can be None if the
448 # information is not available.
449 builtin_limit = limit is BUILTIN_EXCEPTION_LIMIT
450 if limit is None or builtin_limit:
451 limit = getattr(sys, 'tracebacklimit', None)
452 if limit is not None and limit < 0:
453 limit = 0
454 if limit is not None:
455 if builtin_limit:
456 frame_gen = tuple(frame_gen)
457 frame_gen = frame_gen[len(frame_gen) - limit:]
458 # End PyPy 3 change
459 elif limit >= 0:
460 frame_gen = itertools.islice(frame_gen, limit)
461 else:
462 frame_gen = collections.deque(frame_gen, maxlen=-limit)
463
464 result = klass()
465 fnames = set()
466 for f, (lineno, end_lineno, colno, end_colno) in frame_gen:
467 co = f.f_code
468 filename = co.co_filename
469 name = co.co_name
470
471 fnames.add(filename)
472 linecache.lazycache(filename, f.f_globals)
473 # Must defer line lookups until we have called checkcache.
474 if capture_locals:
475 f_locals = f.f_locals
476 else:
477 f_locals = None
478 result.append(FrameSummary(
479 filename, lineno, name, lookup_line=False, locals=f_locals,
480 end_lineno=end_lineno, colno=colno, end_colno=end_colno))
481 for filename in fnames:
482 linecache.checkcache(filename)
483 # If immediate lookup was desired, trigger lookups now.
484 if lookup_lines:
485 for f in result:
486 f.line
487 return result
488
489 @classmethod
490 def from_list(klass, a_list):
491 """
492 Create a StackSummary object from a supplied list of
493 FrameSummary objects or old-style list of tuples.
494 """
495 # While doing a fast-path check for isinstance(a_list, StackSummary) is
496 # appealing, idlelib.run.cleanup_traceback and other similar code may
497 # break this by making arbitrary frames plain tuples, so we need to
498 # check on a frame by frame basis.
499 result = StackSummary()
500 for frame in a_list:
501 if isinstance(frame, FrameSummary):
502 result.append(frame)
503 else:
504 filename, lineno, name, line = frame
505 result.append(FrameSummary(filename, lineno, name, line=line))
506 return result
507
508 def format_frame_summary(self, frame_summary, **kwargs):
509 """Format the lines for a single FrameSummary.
510
511 Returns a string representing one frame involved in the stack. This
512 gets called for every frame to be printed in the stack summary.
513 """
514 # pypy modification: mainly taken from cpy 3.13 to support colors
515 colorize = kwargs.get("colorize", False)
516 row = []
517 filename = frame_summary.filename
518 if colorize:
519 import _colorize
520 from _colorize import ANSIColors
521 row.append(' File {}"{}"{}, line {}{}{}, in {}{}{}\n'.format(
522 ANSIColors.MAGENTA,
523 _filelink(filename),
524 ANSIColors.RESET,
525 ANSIColors.MAGENTA,
526 frame_summary.lineno,
527 ANSIColors.RESET,
528 ANSIColors.MAGENTA,
529 frame_summary.name,
530 ANSIColors.RESET,
531 )
532 )
533 else:
534 row.append(' File "{}", line {}, in {}\n'.format(
535 filename, frame_summary.lineno, frame_summary.name))
536 if frame_summary.line:
537 stripped_line = frame_summary.line.strip()
538 row.append(' {}\n'.format(stripped_line))
539
540 line = frame_summary._original_line
541 orig_line_len = len(line)
542 orig_lstripped_len = len(line.lstrip())
543 n_lstripped = orig_line_len - orig_lstripped_len
544 if (
545 frame_summary.colno is not None
546 and frame_summary.end_colno is not None
547 ):
548 start_offset = _byte_offset_to_character_offset(
549 line, frame_summary.colno)
550 end_offset = _byte_offset_to_character_offset(
551 line, frame_summary.end_colno)
552 code_segment = line[start_offset:end_offset]
553
554 anchors = None
555 if frame_summary.lineno == frame_summary.end_lineno:
556 with suppress(Exception):
557 anchors = _extract_caret_anchors_from_line_segment(code_segment)
558 else:
559 # Don't count the newline since the anchors only need to
560 # go up until the last character of the line.
561 end_offset = len(line.rstrip())
562
563 # show indicators if primary char doesn't span the frame line
564 if end_offset - start_offset < len(stripped_line) or (
565 anchors and anchors.right_start_offset - anchors.left_end_offset > 0):
566
567 if colorize:
568 colorized_line = "".join([
569 " ",
570 stripped_line[:start_offset-n_lstripped],
571 ANSIColors.BOLD_RED,
572 code_segment,
573 ANSIColors.RESET,
574 stripped_line[end_offset-n_lstripped:],
575 "\n",
576 ])
577 row[-1] = colorized_line
578
579 # When showing this on a terminal, some of the non-ASCII characters
580 # might be rendered as double-width characters, so we need to take
581 # that into account when calculating the length of the line.
582 dp_start_offset = _display_width(line, start_offset)
583 dp_end_offset = _display_width(line, end_offset)
584
585 row.append(' ')
586 row.append(' ' * (dp_start_offset - n_lstripped))
587
588 if anchors:
589 dp_left_end_offset = _display_width(code_segment, anchors.left_end_offset)
590 dp_right_start_offset = _display_width(code_segment, anchors.right_start_offset)
591 if colorize:
592 row.append(ANSIColors.BOLD_RED)
593 row.append(anchors.primary_char * dp_left_end_offset)
594 row.append(anchors.secondary_char * (dp_right_start_offset - dp_left_end_offset))
595 row.append(anchors.primary_char * (dp_end_offset - dp_start_offset - dp_right_start_offset))
596 if colorize:
597 row.append(ANSIColors.RESET)
598 else:
599 if colorize:
600 row.append(ANSIColors.BOLD_RED)
601 row.append('^' * (dp_end_offset - dp_start_offset))
602 if colorize:
603 row.append(ANSIColors.RESET)
604
605 row.append('\n')
606
607 # End PyPy3 change
608 if frame_summary.locals:
609 for name, value in sorted(frame_summary.locals.items()):
610 row.append(' {name} = {value}\n'.format(name=name, value=value))
611 return ''.join(row)
612
613 def format(self, colorize=False):
614 """Format the stack ready for printing.
615
616 Returns a list of strings ready for printing. Each string in the
617 resulting list corresponds to a single frame from the stack.
618 Each string ends in a newline; the strings may contain internal
619 newlines as well, for those items with source text lines.
620
621 For long sequences of the same frame and line, the first few
622 repetitions are shown, followed by a summary line stating the exact
623 number of further repetitions.
624 """
625 result = []
626 last_file = None
627 last_line = None
628 last_name = None
629 count = 0
630 for frame_summary in self:
631 formatted_frame = self.format_frame_summary(frame_summary, colorize=colorize)
632 assert formatted_frame is not None
633 if (last_file is None or last_file != frame_summary.filename or
634 last_line is None or last_line != frame_summary.lineno or
635 last_name is None or last_name != frame_summary.name):
636 if count > _RECURSIVE_CUTOFF:
637 count -= _RECURSIVE_CUTOFF
638 result.append(
639 f' [Previous line repeated {count} more '
640 f'time{"s" if count > 1 else ""}]\n'
641 )
642 last_file = frame_summary.filename
643 last_line = frame_summary.lineno
644 last_name = frame_summary.name
645 count = 0
646 count += 1
647 if count > _RECURSIVE_CUTOFF:
648 continue
649 result.append(formatted_frame)
650 if count > _RECURSIVE_CUTOFF:
651 count -= _RECURSIVE_CUTOFF
652 result.append(
653 f' [Previous line repeated {count} more '
654 f'time{"s" if count > 1 else ""}]\n'
655 )
656 return result
657
658 def _byte_offset_to_character_offset(str, offset):
659 as_utf8 = str.encode('utf-8')
660 return len(as_utf8[:offset].decode("utf-8", errors="replace"))
661
662 _Anchors = collections.namedtuple(
663 "_Anchors",
664 [
665 "left_end_offset",
666 "right_start_offset",
667 "primary_char",
668 "secondary_char",
669 ],
670 defaults=["~", "^"]
671 )
672
673 def _extract_caret_anchors_from_line_segment(segment):
674 import ast
675
676 try:
677 tree = ast.parse(segment)
678 except SyntaxError:
679 return None
680
681 if len(tree.body) != 1:
682 return None
683
684 normalize = lambda offset: _byte_offset_to_character_offset(segment, offset)
685 statement = tree.body[0]
686 match statement:
687 case ast.Expr(expr):
688 match expr:
689 case ast.BinOp():
690 operator_start = normalize(expr.left.end_col_offset)
691 operator_end = normalize(expr.right.col_offset)
692 operator_str = segment[operator_start:operator_end]
693 operator_offset = len(operator_str) - len(operator_str.lstrip())
694
695 left_anchor = expr.left.end_col_offset + operator_offset
696 right_anchor = left_anchor + 1
697 if (
698 operator_offset + 1 < len(operator_str)
699 and not operator_str[operator_offset + 1].isspace()
700 ):
701 right_anchor += 1
702
703 while left_anchor < len(segment) and ((ch := segment[left_anchor]).isspace() or ch in ")#"):
704 left_anchor += 1
705 right_anchor += 1
706 return _Anchors(normalize(left_anchor), normalize(right_anchor))
707 case ast.Subscript():
708 left_anchor = normalize(expr.value.end_col_offset)
709 right_anchor = normalize(expr.slice.end_col_offset + 1)
710 while left_anchor < len(segment) and ((ch := segment[left_anchor]).isspace() or ch != "["):
711 left_anchor += 1
712 while right_anchor < len(segment) and ((ch := segment[right_anchor]).isspace() or ch != "]"):
713 right_anchor += 1
714 if right_anchor < len(segment):
715 right_anchor += 1
716 return _Anchors(left_anchor, right_anchor)
717
718 return None
719
720 _WIDE_CHAR_SPECIFIERS = "WF"
721
722 def _display_width(line, offset):
723 """Calculate the extra amount of width space the given source
724 code segment might take if it were to be displayed on a fixed
725 width output device. Supports wide unicode characters and emojis."""
726
727 # Fast track for ASCII-only strings
728 if line.isascii():
729 return offset
730
731 import unicodedata
732
733 return sum(
734 2 if unicodedata.east_asian_width(char) in _WIDE_CHAR_SPECIFIERS else 1
735 for char in line[:offset]
736 )
737
738
739 class _ExceptionPrintContext:
740 def __init__(self):
741 self.seen = set()
742 self.exception_group_depth = 0
743 self.need_close = False
744
745 def indent(self):
746 return ' ' * (2 * self.exception_group_depth)
747
748 def emit(self, text_gen, margin_char=None):
749 if margin_char is None:
750 margin_char = '|'
751 indent_str = self.indent()
752 if self.exception_group_depth:
753 indent_str += margin_char + ' '
754
755 if isinstance(text_gen, str):
756 yield textwrap.indent(text_gen, indent_str, lambda line: True)
757 else:
758 for text in text_gen:
759 yield textwrap.indent(text, indent_str, lambda line: True)
760
761 class TracebackException:
762 """An exception ready for rendering.
763
764 The traceback module captures enough attributes from the original exception
765 to this intermediary form to ensure that no references are held, while
766 still being able to fully print or format it.
767
768 Use `from_exception` to create TracebackException instances from exception
769 objects, or the constructor to create TracebackException instances from
770 individual components.
771
772 - :attr:`__cause__` A TracebackException of the original *__cause__*.
773 - :attr:`__context__` A TracebackException of the original *__context__*.
774 - :attr:`__suppress_context__` The *__suppress_context__* value from the
775 original exception.
776 - :attr:`stack` A `StackSummary` representing the traceback.
777 - :attr:`exc_type` The class of the original traceback.
778 - :attr:`filename` For syntax errors - the filename where the error
779 occurred.
780 - :attr:`lineno` For syntax errors - the linenumber where the error
781 occurred.
782 - :attr:`end_lineno` For syntax errors - the end linenumber where the error
783 occurred. Can be `None` if not present.
784 - :attr:`text` For syntax errors - the text where the error
785 occurred.
786 - :attr:`offset` For syntax errors - the offset into the text where the
787 error occurred.
788 - :attr:`end_offset` For syntax errors - the end offset into the text where
789 the error occurred. Can be `None` if not present.
790 - :attr:`msg` For syntax errors - the compiler error message.
791 """
792
793 def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
794 lookup_lines=True, capture_locals=False, compact=False,
795 max_group_width=15, max_group_depth=10, _seen=None):
796 # NB: we need to accept exc_traceback, exc_value, exc_traceback to
797 # permit backwards compat with the existing API, otherwise we
798 # need stub thunk objects just to glue it together.
799 # Handle loops in __cause__ or __context__.
800 is_recursive_call = _seen is not None
801 if _seen is None:
802 _seen = set()
803 _seen.add(id(exc_value))
804
805 self.max_group_width = max_group_width
806 self.max_group_depth = max_group_depth
807
808 # TODO: locals.
809 self.stack = StackSummary._extract_from_extended_frame_gen(
810 _walk_tb_with_full_positions(exc_traceback),
811 limit=limit, lookup_lines=lookup_lines,
812 capture_locals=capture_locals)
813 self.exc_type = exc_type
814 # Capture now to permit freeing resources: only complication is in the
815 # unofficial API _format_final_exc_line
816 self._str = _safe_string(exc_value, 'exception')
817 try:
818 self.__notes__ = getattr(exc_value, '__notes__', None)
819 except Exception as e:
820 self.__notes__ = [
821 f'Ignored error getting __notes__: {_safe_string(e, "__notes__", repr)}']
822 if exc_type and issubclass(exc_type, SyntaxError):
823 # Handle SyntaxError's specially
824 self.filename = exc_value.filename
825 lno = exc_value.lineno
826 self.lineno = str(lno) if lno is not None else None
827 end_lno = exc_value.end_lineno
828 self.end_lineno = str(end_lno) if end_lno is not None else None
829 self.text = exc_value.text
830 self.offset = exc_value.offset
831 self.end_offset = exc_value.end_offset
832 self.msg = exc_value.msg
833 elif exc_type and issubclass(exc_type, (NameError, AttributeError)) and \
834 getattr(exc_value, "name", None) is not None:
835 # PyPy3 change: backport suggestions
836 wrong_name = getattr(exc_value, "name", None)
837 suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name)
838 if suggestion:
839 self._str += f". Did you mean: '{suggestion}'?"
840 if issubclass(exc_type, NameError):
841 wrong_name = getattr(exc_value, "name", None)
842 if wrong_name is not None and wrong_name in sys.stdlib_module_names:
843 if suggestion:
844 self._str += f" Or did you forget to import '{wrong_name}'"
845 else:
846 self._str += f". Did you forget to import '{wrong_name}'"
847 if lookup_lines:
848 self._load_lines()
849 self.__suppress_context__ = \
850 exc_value.__suppress_context__ if exc_value is not None else False
851
852 # Convert __cause__ and __context__ to `TracebackExceptions`s, use a
853 # queue to avoid recursion (only the top-level call gets _seen == None)
854 if not is_recursive_call:
855 queue = [(self, exc_value)]
856 while queue:
857 te, e = queue.pop()
858 if (e and e.__cause__ is not None
859 and id(e.__cause__) not in _seen):
860 cause = TracebackException(
861 type(e.__cause__),
862 e.__cause__,
863 e.__cause__.__traceback__,
864 limit=limit,
865 lookup_lines=lookup_lines,
866 capture_locals=capture_locals,
867 max_group_width=max_group_width,
868 max_group_depth=max_group_depth,
869 _seen=_seen)
870 else:
871 cause = None
872
873 if compact:
874 need_context = (cause is None and
875 e is not None and
876 not e.__suppress_context__)
877 else:
878 need_context = True
879 if (e and e.__context__ is not None
880 and need_context and id(e.__context__) not in _seen):
881 context = TracebackException(
882 type(e.__context__),
883 e.__context__,
884 e.__context__.__traceback__,
885 limit=limit,
886 lookup_lines=lookup_lines,
887 capture_locals=capture_locals,
888 max_group_width=max_group_width,
889 max_group_depth=max_group_depth,
890 _seen=_seen)
891 else:
892 context = None
893
894 if e and isinstance(e, BaseExceptionGroup):
895 exceptions = []
896 for exc in e.exceptions:
897 texc = TracebackException(
898 type(exc),
899 exc,
900 exc.__traceback__,
901 limit=limit,
902 lookup_lines=lookup_lines,
903 capture_locals=capture_locals,
904 max_group_width=max_group_width,
905 max_group_depth=max_group_depth,
906 _seen=_seen)
907 exceptions.append(texc)
908 else:
909 exceptions = None
910
911 te.__cause__ = cause
912 te.__context__ = context
913 te.exceptions = exceptions
914 if cause:
915 queue.append((te.__cause__, e.__cause__))
916 if context:
917 queue.append((te.__context__, e.__context__))
918 if exceptions:
919 queue.extend(zip(te.exceptions, e.exceptions))
920
921 @classmethod
922 def from_exception(cls, exc, *args, **kwargs):
923 """Create a TracebackException from an exception."""
924 return cls(type(exc), exc, exc.__traceback__, *args, **kwargs)
925
926 def _load_lines(self):
927 """Private API. force all lines in the stack to be loaded."""
928 for frame in self.stack:
929 frame.line
930
931 def __eq__(self, other):
932 if isinstance(other, TracebackException):
933 return self.__dict__ == other.__dict__
934 return NotImplemented
935
936 def __str__(self):
937 return self._str
938
939 def format_exception_only(self):
940 """Format the exception part of the traceback.
941
942 The return value is a generator of strings, each ending in a newline.
943
944 Generator yields the exception message.
945 For :exc:`SyntaxError` exceptions, it
946 also yields (before the exception message)
947 several lines that (when printed)
948 display detailed information about where the syntax error occurred.
949 Following the message, generator also yields
950 all the exception's ``__notes__``.
951 """
952 if self.exc_type is None:
953 yield _format_final_exc_line(None, self._str, colorize=getattr(self, "_colorize", False))
954 return
955
956 stype = self.exc_type.__qualname__
957 smod = self.exc_type.__module__
958 if smod not in ("__main__", "builtins"):
959 if not isinstance(smod, str):
960 smod = "<unknown>"
961 stype = smod + '.' + stype
962
963 if not issubclass(self.exc_type, SyntaxError):
964 yield _format_final_exc_line(stype, self._str, colorize=getattr(self, "_colorize", False))
965 else:
966 yield from self._format_syntax_error(stype)
967 if isinstance(self.__notes__, collections.abc.Sequence):
968 for note in self.__notes__:
969 note = _safe_string(note, 'note')
970 yield from [l + '\n' for l in note.split('\n')]
971 elif self.__notes__ is not None:
972 yield _safe_string(self.__notes__, '__notes__', func=repr)
973
974 def _format_syntax_error(self, stype):
975 """Format SyntaxError exceptions (internal helper)."""
976 # Show exactly where the problem was found.
977 filename_suffix = ''
978 if self.lineno is not None:
979 fn = self.filename or "<string>"
980 if getattr(self, "_colorize", False):
981 from _colorize import ANSIColors
982 yield f' File {ANSIColors.MAGENTA}"{fn}"{ANSIColors.RESET}, line {ANSIColors.MAGENTA}{self.lineno}{ANSIColors.RESET}\n'
983 else:
984 yield ' File "{}", line {}\n'.format(
985 self.filename or "<string>", self.lineno)
986 elif self.filename is not None:
987 filename_suffix = ' ({})'.format(self.filename)
988
989 text = self.text
990 if text is not None:
991 # text = " foo\n"
992 # rtext = " foo"
993 # ltext = "foo"
994 rtext = text.rstrip('\n')
995 ltext = rtext.lstrip(' \n\f')
996 spaces = len(rtext) - len(ltext)
997 if self.offset is None:
998 yield ' {}\n'.format(ltext)
999 else:
1000 offset = self.offset
1001 end_offset = self.end_offset if self.end_offset not in {None, 0} else offset
1002 # Clamp end_offset to text length (C: end_offset = line_size + 1)
1003 if self.text and end_offset > len(rtext) + 1:
1004 end_offset = len(rtext) + 1
1005 # Mirror C logic: if end_offset <= 0 or end_offset <= offset, use 1 caret
1006 if end_offset <= 0 or end_offset <= offset:
1007 end_offset = offset + 1
1008
1009 # Convert 1-based column offset to 0-based index into stripped text
1010 colno = offset - 1 - spaces
1011 end_colno = end_offset - 1 - spaces
1012 if colno >= 0:
1013 caretspace = ((c if c.isspace() else ' ') for c in ltext[:colno])
1014 start_color = end_color = ""
1015 if getattr(self, "_colorize", False):
1016 # print(f"colorize from colno {colno} to {end_colno}")
1017 start_color = ANSIColors.BOLD_RED
1018 end_color = ANSIColors.RESET
1019 ltext = (
1020 ltext[:colno] +
1021 start_color + ltext[colno:end_colno] + end_color +
1022 ltext[end_colno:]
1023 )
1024 yield ' {}\n'.format(ltext)
1025 # non-space whitespace (likes tabs) must be kept for alignment
1026 yield ' {}{}{}{}\n'.format(
1027 "".join(caretspace),
1028 start_color,
1029 ('^' * (end_colno - colno)),
1030 end_color,
1031 )
1032 else:
1033 yield ' {}\n'.format(ltext)
1034 msg = self.msg or "<no detail available>"
1035 yield "{}: {}{}\n".format(stype, msg, filename_suffix)
1036
1037 def format(self, *, chain=True, _ctx=None):
1038 """Format the exception.
1039
1040 If chain is not *True*, *__cause__* and *__context__* will not be formatted.
1041
1042 The return value is a generator of strings, each ending in a newline and
1043 some containing internal newlines. `print_exception` is a wrapper around
1044 this method which just prints the lines to a file.
1045
1046 The message indicating which exception occurred is always the last
1047 string in the output.
1048 """
1049
1050 if _ctx is None:
1051 _ctx = _ExceptionPrintContext()
1052
1053 output = []
1054 exc = self
1055 if chain:
1056 while exc:
1057 if exc.__cause__ is not None:
1058 chained_msg = _cause_message
1059 chained_exc = exc.__cause__
1060 elif (exc.__context__ is not None and
1061 not exc.__suppress_context__):
1062 chained_msg = _context_message
1063 chained_exc = exc.__context__
1064 else:
1065 chained_msg = None
1066 chained_exc = None
1067
1068 output.append((chained_msg, exc))
1069 exc = chained_exc
1070 else:
1071 output.append((None, exc))
1072
1073 for msg, exc in reversed(output):
1074 if msg is not None:
1075 yield from _ctx.emit(msg)
1076 if exc.exceptions is None:
1077 if exc.stack:
1078 yield from _ctx.emit('Traceback (most recent call last):\n')
1079 yield from _ctx.emit(exc.stack.format(colorize=getattr(self, "_colorize", False)))
1080 yield from _ctx.emit(exc.format_exception_only())
1081 elif _ctx.exception_group_depth > self.max_group_depth:
1082 # exception group, but depth exceeds limit
1083 yield from _ctx.emit(
1084 f"... (max_group_depth is {self.max_group_depth})\n")
1085 else:
1086 # format exception group
1087 is_toplevel = (_ctx.exception_group_depth == 0)
1088 if is_toplevel:
1089 _ctx.exception_group_depth += 1
1090
1091 if exc.stack:
1092 yield from _ctx.emit(
1093 'Exception Group Traceback (most recent call last):\n',
1094 margin_char = '+' if is_toplevel else None)
1095 yield from _ctx.emit(exc.stack.format(colorize=getattr(self, "_colorize", False)))
1096
1097 yield from _ctx.emit(exc.format_exception_only())
1098 num_excs = len(exc.exceptions)
1099 if num_excs <= self.max_group_width:
1100 n = num_excs
1101 else:
1102 n = self.max_group_width + 1
1103 _ctx.need_close = False
1104 for i in range(n):
1105 last_exc = (i == n-1)
1106 if last_exc:
1107 # The closing frame may be added by a recursive call
1108 _ctx.need_close = True
1109
1110 if self.max_group_width is not None:
1111 truncated = (i >= self.max_group_width)
1112 else:
1113 truncated = False
1114 title = f'{i+1}' if not truncated else '...'
1115 yield (_ctx.indent() +
1116 ('+-' if i==0 else ' ') +
1117 f'+---------------- {title} ----------------\n')
1118 _ctx.exception_group_depth += 1
1119 if not truncated:
1120 yield from exc.exceptions[i].format(chain=chain, _ctx=_ctx)
1121 else:
1122 remaining = num_excs - self.max_group_width
1123 plural = 's' if remaining > 1 else ''
1124 yield from _ctx.emit(
1125 f"and {remaining} more exception{plural}\n")
1126
1127 if last_exc and _ctx.need_close:
1128 yield (_ctx.indent() +
1129 "+------------------------------------\n")
1130 _ctx.need_close = False
1131 _ctx.exception_group_depth -= 1
1132
1133 if is_toplevel:
1134 assert _ctx.exception_group_depth == 1
1135 _ctx.exception_group_depth = 0
1136
1137
1138 def print(self, *, file=None, chain=True):
1139 """Print the result of self.format(chain=chain) to 'file'."""
1140 if file is None:
1141 file = sys.stderr
1142 for line in self.format(chain=chain):
1143 print(line, file=file, end="")
1144
1145 # PyPy change: backport of the 3.12 pure python suggestion implementation
1146
1147 _MAX_CANDIDATE_ITEMS = 750
1148 _MAX_STRING_SIZE = 80
1149 _MOVE_COST = 2
1150 _CASE_COST = 1
1151
1152
1153 def _substitution_cost(ch_a, ch_b):
1154 if ch_a == ch_b:
1155 return 0
1156 if ch_a.lower() == ch_b.lower():
1157 return _CASE_COST
1158 return _MOVE_COST
1159
1160
1161 def _compute_suggestion_error(exc_value, tb, wrong_name):
1162 if wrong_name is None or not isinstance(wrong_name, str):
1163 return None
1164 if isinstance(exc_value, AttributeError):
1165 obj = exc_value.obj
1166 try:
1167 d = dir(obj)
1168 except Exception:
1169 return None
1170 elif isinstance(exc_value, ImportError):
1171 try:
1172 mod = __import__(exc_value.name)
1173 d = dir(mod)
1174 except Exception:
1175 return None
1176 else:
1177 assert isinstance(exc_value, NameError)
1178 # find most recent frame
1179 if tb is None:
1180 return None
1181 while tb.tb_next is not None:
1182 tb = tb.tb_next
1183 frame = tb.tb_frame
1184 d = (
1185 list(frame.f_locals)
1186 + list(frame.f_globals)
1187 + list(frame.f_builtins)
1188 )
1189
1190 # Check first if we are in a method and the instance
1191 # has the wrong name as attribute
1192 if 'self' in frame.f_locals:
1193 self = frame.f_locals['self']
1194 if hasattr(self, wrong_name):
1195 return f"self.{wrong_name}"
1196
1197 # Compute closest match
1198
1199 if len(d) > _MAX_CANDIDATE_ITEMS:
1200 return None
1201 wrong_name_len = len(wrong_name)
1202 if wrong_name_len > _MAX_STRING_SIZE:
1203 return None
1204 best_distance = wrong_name_len
1205 suggestion = None
1206 for possible_name in d:
1207 if possible_name == wrong_name:
1208 # A missing attribute is "found". Don't suggest it (see GH-88821).
1209 continue
1210 # No more than 1/3 of the involved characters should need changed.
1211 max_distance = (len(possible_name) + wrong_name_len + 3) * _MOVE_COST // 6
1212 # Don't take matches we've already beaten.
1213 max_distance = min(max_distance, best_distance - 1)
1214 current_distance = _levenshtein_distance(wrong_name, possible_name, max_distance)
1215 if current_distance > max_distance:
1216 continue
1217 if not suggestion or current_distance < best_distance:
1218 suggestion = possible_name
1219 best_distance = current_distance
1220 return suggestion
1221
1222
1223 def _levenshtein_distance(a, b, max_cost):
1224 # A Python implementation of Python/suggestions.c:levenshtein_distance.
1225
1226 # Both strings are the same
1227 if a == b:
1228 return 0
1229
1230 # Trim away common affixes
1231 pre = 0
1232 while a[pre:] and b[pre:] and a[pre] == b[pre]:
1233 pre += 1
1234 a = a[pre:]
1235 b = b[pre:]
1236 post = 0
1237 while a[:post or None] and b[:post or None] and a[post-1] == b[post-1]:
1238 post -= 1
1239 a = a[:post or None]
1240 b = b[:post or None]
1241 if not a or not b:
1242 return _MOVE_COST * (len(a) + len(b))
1243 if len(a) > _MAX_STRING_SIZE or len(b) > _MAX_STRING_SIZE:
1244 return max_cost + 1
1245
1246 # Prefer shorter buffer
1247 if len(b) < len(a):
1248 a, b = b, a
1249
1250 # Quick fail when a match is impossible
1251 if (len(b) - len(a)) * _MOVE_COST > max_cost:
1252 return max_cost + 1
1253
1254 # Instead of producing the whole traditional len(a)-by-len(b)
1255 # matrix, we can update just one row in place.
1256 # Initialize the buffer row
1257 row = list(range(_MOVE_COST, _MOVE_COST * (len(a) + 1), _MOVE_COST))
1258
1259 result = 0
1260 for bindex in range(len(b)):
1261 bchar = b[bindex]
1262 distance = result = bindex * _MOVE_COST
1263 minimum = sys.maxsize
1264 for index in range(len(a)):
1265 # 1) Previous distance in this row is cost(b[:b_index], a[:index])
1266 substitute = distance + _substitution_cost(bchar, a[index])
1267 # 2) cost(b[:b_index], a[:index+1]) from previous row
1268 distance = row[index]
1269 # 3) existing result is cost(b[:b_index+1], a[index])
1270
1271 insert_delete = min(result, distance) + _MOVE_COST
1272 result = min(insert_delete, substitute)
1273
1274 # cost(b[:b_index+1], a[:index+1])
1275 row[index] = result
1276 if result < minimum:
1277 minimum = result
1278 if minimum > max_cost:
1279 # Everything in this row is too big, so bail early.
1280 return max_cost + 1
1281 return result