traceback.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. """Extract, format and print information about Python stack traces."""
  2. import collections.abc
  3. import itertools
  4. import linecache
  5. import sys
  6. import textwrap
  7. from contextlib import suppress
  8. __all__ = ['extract_stack', 'extract_tb', 'format_exception',
  9. 'format_exception_only', 'format_list', 'format_stack',
  10. 'format_tb', 'print_exc', 'format_exc', 'print_exception',
  11. 'print_last', 'print_stack', 'print_tb', 'clear_frames',
  12. 'FrameSummary', 'StackSummary', 'TracebackException',
  13. 'walk_stack', 'walk_tb']
  14. #
  15. # Formatting and printing lists of traceback lines.
  16. #
  17. def print_list(extracted_list, file=None):
  18. """Print the list of tuples as returned by extract_tb() or
  19. extract_stack() as a formatted stack trace to the given file."""
  20. if file is None:
  21. file = sys.stderr
  22. for item in StackSummary.from_list(extracted_list).format():
  23. print(item, file=file, end="")
  24. def format_list(extracted_list):
  25. """Format a list of tuples or FrameSummary objects for printing.
  26. Given a list of tuples or FrameSummary objects as returned by
  27. extract_tb() or extract_stack(), return a list of strings ready
  28. for printing.
  29. Each string in the resulting list corresponds to the item with the
  30. same index in the argument list. Each string ends in a newline;
  31. the strings may contain internal newlines as well, for those items
  32. whose source text line is not None.
  33. """
  34. return StackSummary.from_list(extracted_list).format()
  35. #
  36. # Printing and Extracting Tracebacks.
  37. #
  38. def print_tb(tb, limit=None, file=None):
  39. """Print up to 'limit' stack trace entries from the traceback 'tb'.
  40. If 'limit' is omitted or None, all entries are printed. If 'file'
  41. is omitted or None, the output goes to sys.stderr; otherwise
  42. 'file' should be an open file or file-like object with a write()
  43. method.
  44. """
  45. print_list(extract_tb(tb, limit=limit), file=file)
  46. def format_tb(tb, limit=None):
  47. """A shorthand for 'format_list(extract_tb(tb, limit))'."""
  48. return extract_tb(tb, limit=limit).format()
  49. def extract_tb(tb, limit=None):
  50. """
  51. Return a StackSummary object representing a list of
  52. pre-processed entries from traceback.
  53. This is useful for alternate formatting of stack traces. If
  54. 'limit' is omitted or None, all entries are extracted. A
  55. pre-processed stack trace entry is a FrameSummary object
  56. containing attributes filename, lineno, name, and line
  57. representing the information that is usually printed for a stack
  58. trace. The line is a string with leading and trailing
  59. whitespace stripped; if the source is not available it is None.
  60. """
  61. return StackSummary._extract_from_extended_frame_gen(
  62. _walk_tb_with_full_positions(tb), limit=limit)
  63. #
  64. # Exception formatting and output.
  65. #
  66. _cause_message = (
  67. "\nThe above exception was the direct cause "
  68. "of the following exception:\n\n")
  69. _context_message = (
  70. "\nDuring handling of the above exception, "
  71. "another exception occurred:\n\n")
  72. class _Sentinel:
  73. def __repr__(self):
  74. return "<implicit>"
  75. _sentinel = _Sentinel()
  76. def _parse_value_tb(exc, value, tb):
  77. if (value is _sentinel) != (tb is _sentinel):
  78. raise ValueError("Both or neither of value and tb must be given")
  79. if value is tb is _sentinel:
  80. if exc is not None:
  81. if isinstance(exc, BaseException):
  82. return exc, exc.__traceback__
  83. raise TypeError(f'Exception expected for value, '
  84. f'{type(exc).__name__} found')
  85. else:
  86. return None, None
  87. return value, tb
  88. def print_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \
  89. file=None, chain=True):
  90. """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
  91. This differs from print_tb() in the following ways: (1) if
  92. traceback is not None, it prints a header "Traceback (most recent
  93. call last):"; (2) it prints the exception type and value after the
  94. stack trace; (3) if type is SyntaxError and value has the
  95. appropriate format, it prints the line where the syntax error
  96. occurred with a caret on the next line indicating the approximate
  97. position of the error.
  98. """
  99. value, tb = _parse_value_tb(exc, value, tb)
  100. te = TracebackException(type(value), value, tb, limit=limit, compact=True)
  101. te.print(file=file, chain=chain)
  102. def format_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \
  103. chain=True):
  104. """Format a stack trace and the exception information.
  105. The arguments have the same meaning as the corresponding arguments
  106. to print_exception(). The return value is a list of strings, each
  107. ending in a newline and some containing internal newlines. When
  108. these lines are concatenated and printed, exactly the same text is
  109. printed as does print_exception().
  110. """
  111. value, tb = _parse_value_tb(exc, value, tb)
  112. te = TracebackException(type(value), value, tb, limit=limit, compact=True)
  113. return list(te.format(chain=chain))
  114. def format_exception_only(exc, /, value=_sentinel):
  115. """Format the exception part of a traceback.
  116. The return value is a list of strings, each ending in a newline.
  117. Normally, the list contains a single string; however, for
  118. SyntaxError exceptions, it contains several lines that (when
  119. printed) display detailed information about where the syntax
  120. error occurred.
  121. The message indicating which exception occurred is always the last
  122. string in the list.
  123. """
  124. if value is _sentinel:
  125. value = exc
  126. te = TracebackException(type(value), value, None, compact=True)
  127. return list(te.format_exception_only())
  128. # -- not official API but folk probably use these two functions.
  129. def _format_final_exc_line(etype, value):
  130. valuestr = _safe_string(value, 'exception')
  131. if value is None or not valuestr:
  132. line = "%s\n" % etype
  133. else:
  134. line = "%s: %s\n" % (etype, valuestr)
  135. return line
  136. def _safe_string(value, what, func=str):
  137. try:
  138. return func(value)
  139. except:
  140. return f'<{what} {func.__name__}() failed>'
  141. # --
  142. def print_exc(limit=None, file=None, chain=True):
  143. """Shorthand for 'print_exception(*sys.exc_info(), limit, file)'."""
  144. print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain)
  145. def format_exc(limit=None, chain=True):
  146. """Like print_exc() but return a string."""
  147. return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain))
  148. def print_last(limit=None, file=None, chain=True):
  149. """This is a shorthand for 'print_exception(sys.last_type,
  150. sys.last_value, sys.last_traceback, limit, file)'."""
  151. if not hasattr(sys, "last_type"):
  152. raise ValueError("no last exception")
  153. print_exception(sys.last_type, sys.last_value, sys.last_traceback,
  154. limit, file, chain)
  155. #
  156. # Printing and Extracting Stacks.
  157. #
  158. def print_stack(f=None, limit=None, file=None):
  159. """Print a stack trace from its invocation point.
  160. The optional 'f' argument can be used to specify an alternate
  161. stack frame at which to start. The optional 'limit' and 'file'
  162. arguments have the same meaning as for print_exception().
  163. """
  164. if f is None:
  165. f = sys._getframe().f_back
  166. print_list(extract_stack(f, limit=limit), file=file)
  167. def format_stack(f=None, limit=None):
  168. """Shorthand for 'format_list(extract_stack(f, limit))'."""
  169. if f is None:
  170. f = sys._getframe().f_back
  171. return format_list(extract_stack(f, limit=limit))
  172. def extract_stack(f=None, limit=None):
  173. """Extract the raw traceback from the current stack frame.
  174. The return value has the same format as for extract_tb(). The
  175. optional 'f' and 'limit' arguments have the same meaning as for
  176. print_stack(). Each item in the list is a quadruple (filename,
  177. line number, function name, text), and the entries are in order
  178. from oldest to newest stack frame.
  179. """
  180. if f is None:
  181. f = sys._getframe().f_back
  182. stack = StackSummary.extract(walk_stack(f), limit=limit)
  183. stack.reverse()
  184. return stack
  185. def clear_frames(tb):
  186. "Clear all references to local variables in the frames of a traceback."
  187. while tb is not None:
  188. try:
  189. tb.tb_frame.clear()
  190. except RuntimeError:
  191. # Ignore the exception raised if the frame is still executing.
  192. pass
  193. tb = tb.tb_next
  194. class FrameSummary:
  195. """Information about a single frame from a traceback.
  196. - :attr:`filename` The filename for the frame.
  197. - :attr:`lineno` The line within filename for the frame that was
  198. active when the frame was captured.
  199. - :attr:`name` The name of the function or method that was executing
  200. when the frame was captured.
  201. - :attr:`line` The text from the linecache module for the
  202. of code that was running when the frame was captured.
  203. - :attr:`locals` Either None if locals were not supplied, or a dict
  204. mapping the name to the repr() of the variable.
  205. """
  206. __slots__ = ('filename', 'lineno', 'end_lineno', 'colno', 'end_colno',
  207. 'name', '_line', 'locals')
  208. def __init__(self, filename, lineno, name, *, lookup_line=True,
  209. locals=None, line=None,
  210. end_lineno=None, colno=None, end_colno=None):
  211. """Construct a FrameSummary.
  212. :param lookup_line: If True, `linecache` is consulted for the source
  213. code line. Otherwise, the line will be looked up when first needed.
  214. :param locals: If supplied the frame locals, which will be captured as
  215. object representations.
  216. :param line: If provided, use this instead of looking up the line in
  217. the linecache.
  218. """
  219. self.filename = filename
  220. self.lineno = lineno
  221. self.name = name
  222. self._line = line
  223. if lookup_line:
  224. self.line
  225. self.locals = {k: repr(v) for k, v in locals.items()} if locals else None
  226. self.end_lineno = end_lineno
  227. self.colno = colno
  228. self.end_colno = end_colno
  229. def __eq__(self, other):
  230. if isinstance(other, FrameSummary):
  231. return (self.filename == other.filename and
  232. self.lineno == other.lineno and
  233. self.name == other.name and
  234. self.locals == other.locals)
  235. if isinstance(other, tuple):
  236. return (self.filename, self.lineno, self.name, self.line) == other
  237. return NotImplemented
  238. def __getitem__(self, pos):
  239. return (self.filename, self.lineno, self.name, self.line)[pos]
  240. def __iter__(self):
  241. return iter([self.filename, self.lineno, self.name, self.line])
  242. def __repr__(self):
  243. return "<FrameSummary file {filename}, line {lineno} in {name}>".format(
  244. filename=self.filename, lineno=self.lineno, name=self.name)
  245. def __len__(self):
  246. return 4
  247. @property
  248. def _original_line(self):
  249. # Returns the line as-is from the source, without modifying whitespace.
  250. self.line
  251. return self._line
  252. @property
  253. def line(self):
  254. if self._line is None:
  255. if self.lineno is None:
  256. return None
  257. self._line = linecache.getline(self.filename, self.lineno)
  258. return self._line.strip()
  259. def walk_stack(f):
  260. """Walk a stack yielding the frame and line number for each frame.
  261. This will follow f.f_back from the given frame. If no frame is given, the
  262. current stack is used. Usually used with StackSummary.extract.
  263. """
  264. if f is None:
  265. f = sys._getframe().f_back.f_back.f_back.f_back
  266. while f is not None:
  267. yield f, f.f_lineno
  268. f = f.f_back
  269. def walk_tb(tb):
  270. """Walk a traceback yielding the frame and line number for each frame.
  271. This will follow tb.tb_next (and thus is in the opposite order to
  272. walk_stack). Usually used with StackSummary.extract.
  273. """
  274. while tb is not None:
  275. yield tb.tb_frame, tb.tb_lineno
  276. tb = tb.tb_next
  277. def _walk_tb_with_full_positions(tb):
  278. # Internal version of walk_tb that yields full code positions including
  279. # end line and column information.
  280. while tb is not None:
  281. positions = _get_code_position(tb.tb_frame.f_code, tb.tb_lasti)
  282. # Yield tb_lineno when co_positions does not have a line number to
  283. # maintain behavior with walk_tb.
  284. if positions[0] is None:
  285. yield tb.tb_frame, (tb.tb_lineno, ) + positions[1:]
  286. else:
  287. yield tb.tb_frame, positions
  288. tb = tb.tb_next
  289. def _get_code_position(code, instruction_index):
  290. if instruction_index < 0:
  291. return (None, None, None, None)
  292. positions_gen = code.co_positions()
  293. return next(itertools.islice(positions_gen, instruction_index // 2, None))
  294. _RECURSIVE_CUTOFF = 3 # Also hardcoded in traceback.c.
  295. class StackSummary(list):
  296. """A list of FrameSummary objects, representing a stack of frames."""
  297. @classmethod
  298. def extract(klass, frame_gen, *, limit=None, lookup_lines=True,
  299. capture_locals=False):
  300. """Create a StackSummary from a traceback or stack object.
  301. :param frame_gen: A generator that yields (frame, lineno) tuples
  302. whose summaries are to be included in the stack.
  303. :param limit: None to include all frames or the number of frames to
  304. include.
  305. :param lookup_lines: If True, lookup lines for each frame immediately,
  306. otherwise lookup is deferred until the frame is rendered.
  307. :param capture_locals: If True, the local variables from each frame will
  308. be captured as object representations into the FrameSummary.
  309. """
  310. def extended_frame_gen():
  311. for f, lineno in frame_gen:
  312. yield f, (lineno, None, None, None)
  313. return klass._extract_from_extended_frame_gen(
  314. extended_frame_gen(), limit=limit, lookup_lines=lookup_lines,
  315. capture_locals=capture_locals)
  316. @classmethod
  317. def _extract_from_extended_frame_gen(klass, frame_gen, *, limit=None,
  318. lookup_lines=True, capture_locals=False):
  319. # Same as extract but operates on a frame generator that yields
  320. # (frame, (lineno, end_lineno, colno, end_colno)) in the stack.
  321. # Only lineno is required, the remaining fields can be None if the
  322. # information is not available.
  323. if limit is None:
  324. limit = getattr(sys, 'tracebacklimit', None)
  325. if limit is not None and limit < 0:
  326. limit = 0
  327. if limit is not None:
  328. if limit >= 0:
  329. frame_gen = itertools.islice(frame_gen, limit)
  330. else:
  331. frame_gen = collections.deque(frame_gen, maxlen=-limit)
  332. result = klass()
  333. fnames = set()
  334. for f, (lineno, end_lineno, colno, end_colno) in frame_gen:
  335. co = f.f_code
  336. filename = co.co_filename
  337. name = co.co_name
  338. fnames.add(filename)
  339. linecache.lazycache(filename, f.f_globals)
  340. # Must defer line lookups until we have called checkcache.
  341. if capture_locals:
  342. f_locals = f.f_locals
  343. else:
  344. f_locals = None
  345. result.append(FrameSummary(
  346. filename, lineno, name, lookup_line=False, locals=f_locals,
  347. end_lineno=end_lineno, colno=colno, end_colno=end_colno))
  348. for filename in fnames:
  349. linecache.checkcache(filename)
  350. # If immediate lookup was desired, trigger lookups now.
  351. if lookup_lines:
  352. for f in result:
  353. f.line
  354. return result
  355. @classmethod
  356. def from_list(klass, a_list):
  357. """
  358. Create a StackSummary object from a supplied list of
  359. FrameSummary objects or old-style list of tuples.
  360. """
  361. # While doing a fast-path check for isinstance(a_list, StackSummary) is
  362. # appealing, idlelib.run.cleanup_traceback and other similar code may
  363. # break this by making arbitrary frames plain tuples, so we need to
  364. # check on a frame by frame basis.
  365. result = StackSummary()
  366. for frame in a_list:
  367. if isinstance(frame, FrameSummary):
  368. result.append(frame)
  369. else:
  370. filename, lineno, name, line = frame
  371. result.append(FrameSummary(filename, lineno, name, line=line))
  372. return result
  373. def format_frame_summary(self, frame_summary):
  374. """Format the lines for a single FrameSummary.
  375. Returns a string representing one frame involved in the stack. This
  376. gets called for every frame to be printed in the stack summary.
  377. """
  378. row = []
  379. row.append(' File "{}", line {}, in {}\n'.format(
  380. frame_summary.filename, frame_summary.lineno, frame_summary.name))
  381. if frame_summary.line:
  382. stripped_line = frame_summary.line.strip()
  383. row.append(' {}\n'.format(stripped_line))
  384. orig_line_len = len(frame_summary._original_line)
  385. frame_line_len = len(frame_summary.line.lstrip())
  386. stripped_characters = orig_line_len - frame_line_len
  387. if (
  388. frame_summary.colno is not None
  389. and frame_summary.end_colno is not None
  390. ):
  391. start_offset = _byte_offset_to_character_offset(
  392. frame_summary._original_line, frame_summary.colno) + 1
  393. end_offset = _byte_offset_to_character_offset(
  394. frame_summary._original_line, frame_summary.end_colno) + 1
  395. anchors = None
  396. if frame_summary.lineno == frame_summary.end_lineno:
  397. with suppress(Exception):
  398. anchors = _extract_caret_anchors_from_line_segment(
  399. frame_summary._original_line[start_offset - 1:end_offset - 1]
  400. )
  401. else:
  402. end_offset = stripped_characters + len(stripped_line)
  403. # show indicators if primary char doesn't span the frame line
  404. if end_offset - start_offset < len(stripped_line) or (
  405. anchors and anchors.right_start_offset - anchors.left_end_offset > 0):
  406. row.append(' ')
  407. row.append(' ' * (start_offset - stripped_characters))
  408. if anchors:
  409. row.append(anchors.primary_char * (anchors.left_end_offset))
  410. row.append(anchors.secondary_char * (anchors.right_start_offset - anchors.left_end_offset))
  411. row.append(anchors.primary_char * (end_offset - start_offset - anchors.right_start_offset))
  412. else:
  413. row.append('^' * (end_offset - start_offset))
  414. row.append('\n')
  415. if frame_summary.locals:
  416. for name, value in sorted(frame_summary.locals.items()):
  417. row.append(' {name} = {value}\n'.format(name=name, value=value))
  418. return ''.join(row)
  419. def format(self):
  420. """Format the stack ready for printing.
  421. Returns a list of strings ready for printing. Each string in the
  422. resulting list corresponds to a single frame from the stack.
  423. Each string ends in a newline; the strings may contain internal
  424. newlines as well, for those items with source text lines.
  425. For long sequences of the same frame and line, the first few
  426. repetitions are shown, followed by a summary line stating the exact
  427. number of further repetitions.
  428. """
  429. result = []
  430. last_file = None
  431. last_line = None
  432. last_name = None
  433. count = 0
  434. for frame_summary in self:
  435. formatted_frame = self.format_frame_summary(frame_summary)
  436. if formatted_frame is None:
  437. continue
  438. if (last_file is None or last_file != frame_summary.filename or
  439. last_line is None or last_line != frame_summary.lineno or
  440. last_name is None or last_name != frame_summary.name):
  441. if count > _RECURSIVE_CUTOFF:
  442. count -= _RECURSIVE_CUTOFF
  443. result.append(
  444. f' [Previous line repeated {count} more '
  445. f'time{"s" if count > 1 else ""}]\n'
  446. )
  447. last_file = frame_summary.filename
  448. last_line = frame_summary.lineno
  449. last_name = frame_summary.name
  450. count = 0
  451. count += 1
  452. if count > _RECURSIVE_CUTOFF:
  453. continue
  454. result.append(formatted_frame)
  455. if count > _RECURSIVE_CUTOFF:
  456. count -= _RECURSIVE_CUTOFF
  457. result.append(
  458. f' [Previous line repeated {count} more '
  459. f'time{"s" if count > 1 else ""}]\n'
  460. )
  461. return result
  462. def _byte_offset_to_character_offset(str, offset):
  463. as_utf8 = str.encode('utf-8')
  464. return len(as_utf8[:offset].decode("utf-8", errors="replace"))
  465. _Anchors = collections.namedtuple(
  466. "_Anchors",
  467. [
  468. "left_end_offset",
  469. "right_start_offset",
  470. "primary_char",
  471. "secondary_char",
  472. ],
  473. defaults=["~", "^"]
  474. )
  475. def _extract_caret_anchors_from_line_segment(segment):
  476. import ast
  477. try:
  478. tree = ast.parse(segment)
  479. except SyntaxError:
  480. return None
  481. if len(tree.body) != 1:
  482. return None
  483. normalize = lambda offset: _byte_offset_to_character_offset(segment, offset)
  484. statement = tree.body[0]
  485. match statement:
  486. case ast.Expr(expr):
  487. match expr:
  488. case ast.BinOp():
  489. operator_start = normalize(expr.left.end_col_offset)
  490. operator_end = normalize(expr.right.col_offset)
  491. operator_str = segment[operator_start:operator_end]
  492. operator_offset = len(operator_str) - len(operator_str.lstrip())
  493. left_anchor = expr.left.end_col_offset + operator_offset
  494. right_anchor = left_anchor + 1
  495. if (
  496. operator_offset + 1 < len(operator_str)
  497. and not operator_str[operator_offset + 1].isspace()
  498. ):
  499. right_anchor += 1
  500. return _Anchors(normalize(left_anchor), normalize(right_anchor))
  501. case ast.Subscript():
  502. subscript_start = normalize(expr.value.end_col_offset)
  503. subscript_end = normalize(expr.slice.end_col_offset + 1)
  504. return _Anchors(subscript_start, subscript_end)
  505. return None
  506. class _ExceptionPrintContext:
  507. def __init__(self):
  508. self.seen = set()
  509. self.exception_group_depth = 0
  510. self.need_close = False
  511. def indent(self):
  512. return ' ' * (2 * self.exception_group_depth)
  513. def emit(self, text_gen, margin_char=None):
  514. if margin_char is None:
  515. margin_char = '|'
  516. indent_str = self.indent()
  517. if self.exception_group_depth:
  518. indent_str += margin_char + ' '
  519. if isinstance(text_gen, str):
  520. yield textwrap.indent(text_gen, indent_str, lambda line: True)
  521. else:
  522. for text in text_gen:
  523. yield textwrap.indent(text, indent_str, lambda line: True)
  524. class TracebackException:
  525. """An exception ready for rendering.
  526. The traceback module captures enough attributes from the original exception
  527. to this intermediary form to ensure that no references are held, while
  528. still being able to fully print or format it.
  529. max_group_width and max_group_depth control the formatting of exception
  530. groups. The depth refers to the nesting level of the group, and the width
  531. refers to the size of a single exception group's exceptions array. The
  532. formatted output is truncated when either limit is exceeded.
  533. Use `from_exception` to create TracebackException instances from exception
  534. objects, or the constructor to create TracebackException instances from
  535. individual components.
  536. - :attr:`__cause__` A TracebackException of the original *__cause__*.
  537. - :attr:`__context__` A TracebackException of the original *__context__*.
  538. - :attr:`__suppress_context__` The *__suppress_context__* value from the
  539. original exception.
  540. - :attr:`stack` A `StackSummary` representing the traceback.
  541. - :attr:`exc_type` The class of the original traceback.
  542. - :attr:`filename` For syntax errors - the filename where the error
  543. occurred.
  544. - :attr:`lineno` For syntax errors - the linenumber where the error
  545. occurred.
  546. - :attr:`end_lineno` For syntax errors - the end linenumber where the error
  547. occurred. Can be `None` if not present.
  548. - :attr:`text` For syntax errors - the text where the error
  549. occurred.
  550. - :attr:`offset` For syntax errors - the offset into the text where the
  551. error occurred.
  552. - :attr:`end_offset` For syntax errors - the offset into the text where the
  553. error occurred. Can be `None` if not present.
  554. - :attr:`msg` For syntax errors - the compiler error message.
  555. """
  556. def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
  557. lookup_lines=True, capture_locals=False, compact=False,
  558. max_group_width=15, max_group_depth=10, _seen=None):
  559. # NB: we need to accept exc_traceback, exc_value, exc_traceback to
  560. # permit backwards compat with the existing API, otherwise we
  561. # need stub thunk objects just to glue it together.
  562. # Handle loops in __cause__ or __context__.
  563. is_recursive_call = _seen is not None
  564. if _seen is None:
  565. _seen = set()
  566. _seen.add(id(exc_value))
  567. self.max_group_width = max_group_width
  568. self.max_group_depth = max_group_depth
  569. self.stack = StackSummary._extract_from_extended_frame_gen(
  570. _walk_tb_with_full_positions(exc_traceback),
  571. limit=limit, lookup_lines=lookup_lines,
  572. capture_locals=capture_locals)
  573. self.exc_type = exc_type
  574. # Capture now to permit freeing resources: only complication is in the
  575. # unofficial API _format_final_exc_line
  576. self._str = _safe_string(exc_value, 'exception')
  577. self.__notes__ = getattr(exc_value, '__notes__', None)
  578. if exc_type and issubclass(exc_type, SyntaxError):
  579. # Handle SyntaxError's specially
  580. self.filename = exc_value.filename
  581. lno = exc_value.lineno
  582. self.lineno = str(lno) if lno is not None else None
  583. end_lno = exc_value.end_lineno
  584. self.end_lineno = str(end_lno) if end_lno is not None else None
  585. self.text = exc_value.text
  586. self.offset = exc_value.offset
  587. self.end_offset = exc_value.end_offset
  588. self.msg = exc_value.msg
  589. if lookup_lines:
  590. self._load_lines()
  591. self.__suppress_context__ = \
  592. exc_value.__suppress_context__ if exc_value is not None else False
  593. # Convert __cause__ and __context__ to `TracebackExceptions`s, use a
  594. # queue to avoid recursion (only the top-level call gets _seen == None)
  595. if not is_recursive_call:
  596. queue = [(self, exc_value)]
  597. while queue:
  598. te, e = queue.pop()
  599. if (e and e.__cause__ is not None
  600. and id(e.__cause__) not in _seen):
  601. cause = TracebackException(
  602. type(e.__cause__),
  603. e.__cause__,
  604. e.__cause__.__traceback__,
  605. limit=limit,
  606. lookup_lines=lookup_lines,
  607. capture_locals=capture_locals,
  608. max_group_width=max_group_width,
  609. max_group_depth=max_group_depth,
  610. _seen=_seen)
  611. else:
  612. cause = None
  613. if compact:
  614. need_context = (cause is None and
  615. e is not None and
  616. not e.__suppress_context__)
  617. else:
  618. need_context = True
  619. if (e and e.__context__ is not None
  620. and need_context and id(e.__context__) not in _seen):
  621. context = TracebackException(
  622. type(e.__context__),
  623. e.__context__,
  624. e.__context__.__traceback__,
  625. limit=limit,
  626. lookup_lines=lookup_lines,
  627. capture_locals=capture_locals,
  628. max_group_width=max_group_width,
  629. max_group_depth=max_group_depth,
  630. _seen=_seen)
  631. else:
  632. context = None
  633. if e and isinstance(e, BaseExceptionGroup):
  634. exceptions = []
  635. for exc in e.exceptions:
  636. texc = TracebackException(
  637. type(exc),
  638. exc,
  639. exc.__traceback__,
  640. limit=limit,
  641. lookup_lines=lookup_lines,
  642. capture_locals=capture_locals,
  643. max_group_width=max_group_width,
  644. max_group_depth=max_group_depth,
  645. _seen=_seen)
  646. exceptions.append(texc)
  647. else:
  648. exceptions = None
  649. te.__cause__ = cause
  650. te.__context__ = context
  651. te.exceptions = exceptions
  652. if cause:
  653. queue.append((te.__cause__, e.__cause__))
  654. if context:
  655. queue.append((te.__context__, e.__context__))
  656. if exceptions:
  657. queue.extend(zip(te.exceptions, e.exceptions))
  658. @classmethod
  659. def from_exception(cls, exc, *args, **kwargs):
  660. """Create a TracebackException from an exception."""
  661. return cls(type(exc), exc, exc.__traceback__, *args, **kwargs)
  662. def _load_lines(self):
  663. """Private API. force all lines in the stack to be loaded."""
  664. for frame in self.stack:
  665. frame.line
  666. def __eq__(self, other):
  667. if isinstance(other, TracebackException):
  668. return self.__dict__ == other.__dict__
  669. return NotImplemented
  670. def __str__(self):
  671. return self._str
  672. def format_exception_only(self):
  673. """Format the exception part of the traceback.
  674. The return value is a generator of strings, each ending in a newline.
  675. Normally, the generator emits a single string; however, for
  676. SyntaxError exceptions, it emits several lines that (when
  677. printed) display detailed information about where the syntax
  678. error occurred.
  679. The message indicating which exception occurred is always the last
  680. string in the output.
  681. """
  682. if self.exc_type is None:
  683. yield _format_final_exc_line(None, self._str)
  684. return
  685. stype = self.exc_type.__qualname__
  686. smod = self.exc_type.__module__
  687. if smod not in ("__main__", "builtins"):
  688. if not isinstance(smod, str):
  689. smod = "<unknown>"
  690. stype = smod + '.' + stype
  691. if not issubclass(self.exc_type, SyntaxError):
  692. yield _format_final_exc_line(stype, self._str)
  693. else:
  694. yield from self._format_syntax_error(stype)
  695. if isinstance(self.__notes__, collections.abc.Sequence):
  696. for note in self.__notes__:
  697. note = _safe_string(note, 'note')
  698. yield from [l + '\n' for l in note.split('\n')]
  699. elif self.__notes__ is not None:
  700. yield _safe_string(self.__notes__, '__notes__', func=repr)
  701. def _format_syntax_error(self, stype):
  702. """Format SyntaxError exceptions (internal helper)."""
  703. # Show exactly where the problem was found.
  704. filename_suffix = ''
  705. if self.lineno is not None:
  706. yield ' File "{}", line {}\n'.format(
  707. self.filename or "<string>", self.lineno)
  708. elif self.filename is not None:
  709. filename_suffix = ' ({})'.format(self.filename)
  710. text = self.text
  711. if text is not None:
  712. # text = " foo\n"
  713. # rtext = " foo"
  714. # ltext = "foo"
  715. rtext = text.rstrip('\n')
  716. ltext = rtext.lstrip(' \n\f')
  717. spaces = len(rtext) - len(ltext)
  718. yield ' {}\n'.format(ltext)
  719. if self.offset is not None:
  720. offset = self.offset
  721. end_offset = self.end_offset if self.end_offset not in {None, 0} else offset
  722. if offset == end_offset or end_offset == -1:
  723. end_offset = offset + 1
  724. # Convert 1-based column offset to 0-based index into stripped text
  725. colno = offset - 1 - spaces
  726. end_colno = end_offset - 1 - spaces
  727. if colno >= 0:
  728. # non-space whitespace (likes tabs) must be kept for alignment
  729. caretspace = ((c if c.isspace() else ' ') for c in ltext[:colno])
  730. yield ' {}{}'.format("".join(caretspace), ('^' * (end_colno - colno) + "\n"))
  731. msg = self.msg or "<no detail available>"
  732. yield "{}: {}{}\n".format(stype, msg, filename_suffix)
  733. def format(self, *, chain=True, _ctx=None):
  734. """Format the exception.
  735. If chain is not *True*, *__cause__* and *__context__* will not be formatted.
  736. The return value is a generator of strings, each ending in a newline and
  737. some containing internal newlines. `print_exception` is a wrapper around
  738. this method which just prints the lines to a file.
  739. The message indicating which exception occurred is always the last
  740. string in the output.
  741. """
  742. if _ctx is None:
  743. _ctx = _ExceptionPrintContext()
  744. output = []
  745. exc = self
  746. if chain:
  747. while exc:
  748. if exc.__cause__ is not None:
  749. chained_msg = _cause_message
  750. chained_exc = exc.__cause__
  751. elif (exc.__context__ is not None and
  752. not exc.__suppress_context__):
  753. chained_msg = _context_message
  754. chained_exc = exc.__context__
  755. else:
  756. chained_msg = None
  757. chained_exc = None
  758. output.append((chained_msg, exc))
  759. exc = chained_exc
  760. else:
  761. output.append((None, exc))
  762. for msg, exc in reversed(output):
  763. if msg is not None:
  764. yield from _ctx.emit(msg)
  765. if exc.exceptions is None:
  766. if exc.stack:
  767. yield from _ctx.emit('Traceback (most recent call last):\n')
  768. yield from _ctx.emit(exc.stack.format())
  769. yield from _ctx.emit(exc.format_exception_only())
  770. elif _ctx.exception_group_depth > self.max_group_depth:
  771. # exception group, but depth exceeds limit
  772. yield from _ctx.emit(
  773. f"... (max_group_depth is {self.max_group_depth})\n")
  774. else:
  775. # format exception group
  776. is_toplevel = (_ctx.exception_group_depth == 0)
  777. if is_toplevel:
  778. _ctx.exception_group_depth += 1
  779. if exc.stack:
  780. yield from _ctx.emit(
  781. 'Exception Group Traceback (most recent call last):\n',
  782. margin_char = '+' if is_toplevel else None)
  783. yield from _ctx.emit(exc.stack.format())
  784. yield from _ctx.emit(exc.format_exception_only())
  785. num_excs = len(exc.exceptions)
  786. if num_excs <= self.max_group_width:
  787. n = num_excs
  788. else:
  789. n = self.max_group_width + 1
  790. _ctx.need_close = False
  791. for i in range(n):
  792. last_exc = (i == n-1)
  793. if last_exc:
  794. # The closing frame may be added by a recursive call
  795. _ctx.need_close = True
  796. if self.max_group_width is not None:
  797. truncated = (i >= self.max_group_width)
  798. else:
  799. truncated = False
  800. title = f'{i+1}' if not truncated else '...'
  801. yield (_ctx.indent() +
  802. ('+-' if i==0 else ' ') +
  803. f'+---------------- {title} ----------------\n')
  804. _ctx.exception_group_depth += 1
  805. if not truncated:
  806. yield from exc.exceptions[i].format(chain=chain, _ctx=_ctx)
  807. else:
  808. remaining = num_excs - self.max_group_width
  809. plural = 's' if remaining > 1 else ''
  810. yield from _ctx.emit(
  811. f"and {remaining} more exception{plural}\n")
  812. if last_exc and _ctx.need_close:
  813. yield (_ctx.indent() +
  814. "+------------------------------------\n")
  815. _ctx.need_close = False
  816. _ctx.exception_group_depth -= 1
  817. if is_toplevel:
  818. assert _ctx.exception_group_depth == 1
  819. _ctx.exception_group_depth = 0
  820. def print(self, *, file=None, chain=True):
  821. """Print the result of self.format(chain=chain) to 'file'."""
  822. if file is None:
  823. file = sys.stderr
  824. for line in self.format(chain=chain):
  825. print(line, file=file, end="")