traceback.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  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.exception(), limit, file, chain)'."""
  144. print_exception(sys.exception(), 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.exception(), limit=limit, chain=chain))
  148. def print_last(limit=None, file=None, chain=True):
  149. """This is a shorthand for 'print_exception(sys.last_exc, limit, file, chain)'."""
  150. if not hasattr(sys, "last_exc") and not hasattr(sys, "last_type"):
  151. raise ValueError("no last exception")
  152. if hasattr(sys, "last_exc"):
  153. print_exception(sys.last_exc, limit, file, chain)
  154. else:
  155. print_exception(sys.last_type, sys.last_value, sys.last_traceback,
  156. limit, file, chain)
  157. #
  158. # Printing and Extracting Stacks.
  159. #
  160. def print_stack(f=None, limit=None, file=None):
  161. """Print a stack trace from its invocation point.
  162. The optional 'f' argument can be used to specify an alternate
  163. stack frame at which to start. The optional 'limit' and 'file'
  164. arguments have the same meaning as for print_exception().
  165. """
  166. if f is None:
  167. f = sys._getframe().f_back
  168. print_list(extract_stack(f, limit=limit), file=file)
  169. def format_stack(f=None, limit=None):
  170. """Shorthand for 'format_list(extract_stack(f, limit))'."""
  171. if f is None:
  172. f = sys._getframe().f_back
  173. return format_list(extract_stack(f, limit=limit))
  174. def extract_stack(f=None, limit=None):
  175. """Extract the raw traceback from the current stack frame.
  176. The return value has the same format as for extract_tb(). The
  177. optional 'f' and 'limit' arguments have the same meaning as for
  178. print_stack(). Each item in the list is a quadruple (filename,
  179. line number, function name, text), and the entries are in order
  180. from oldest to newest stack frame.
  181. """
  182. if f is None:
  183. f = sys._getframe().f_back
  184. stack = StackSummary.extract(walk_stack(f), limit=limit)
  185. stack.reverse()
  186. return stack
  187. def clear_frames(tb):
  188. "Clear all references to local variables in the frames of a traceback."
  189. while tb is not None:
  190. try:
  191. tb.tb_frame.clear()
  192. except RuntimeError:
  193. # Ignore the exception raised if the frame is still executing.
  194. pass
  195. tb = tb.tb_next
  196. class FrameSummary:
  197. """Information about a single frame from a traceback.
  198. - :attr:`filename` The filename for the frame.
  199. - :attr:`lineno` The line within filename for the frame that was
  200. active when the frame was captured.
  201. - :attr:`name` The name of the function or method that was executing
  202. when the frame was captured.
  203. - :attr:`line` The text from the linecache module for the
  204. of code that was running when the frame was captured.
  205. - :attr:`locals` Either None if locals were not supplied, or a dict
  206. mapping the name to the repr() of the variable.
  207. """
  208. __slots__ = ('filename', 'lineno', 'end_lineno', 'colno', 'end_colno',
  209. 'name', '_line', 'locals')
  210. def __init__(self, filename, lineno, name, *, lookup_line=True,
  211. locals=None, line=None,
  212. end_lineno=None, colno=None, end_colno=None):
  213. """Construct a FrameSummary.
  214. :param lookup_line: If True, `linecache` is consulted for the source
  215. code line. Otherwise, the line will be looked up when first needed.
  216. :param locals: If supplied the frame locals, which will be captured as
  217. object representations.
  218. :param line: If provided, use this instead of looking up the line in
  219. the linecache.
  220. """
  221. self.filename = filename
  222. self.lineno = lineno
  223. self.name = name
  224. self._line = line
  225. if lookup_line:
  226. self.line
  227. self.locals = {k: _safe_string(v, 'local', func=repr)
  228. for k, v in locals.items()} if locals else None
  229. self.end_lineno = end_lineno
  230. self.colno = colno
  231. self.end_colno = end_colno
  232. def __eq__(self, other):
  233. if isinstance(other, FrameSummary):
  234. return (self.filename == other.filename and
  235. self.lineno == other.lineno and
  236. self.name == other.name and
  237. self.locals == other.locals)
  238. if isinstance(other, tuple):
  239. return (self.filename, self.lineno, self.name, self.line) == other
  240. return NotImplemented
  241. def __getitem__(self, pos):
  242. return (self.filename, self.lineno, self.name, self.line)[pos]
  243. def __iter__(self):
  244. return iter([self.filename, self.lineno, self.name, self.line])
  245. def __repr__(self):
  246. return "<FrameSummary file {filename}, line {lineno} in {name}>".format(
  247. filename=self.filename, lineno=self.lineno, name=self.name)
  248. def __len__(self):
  249. return 4
  250. @property
  251. def _original_line(self):
  252. # Returns the line as-is from the source, without modifying whitespace.
  253. self.line
  254. return self._line
  255. @property
  256. def line(self):
  257. if self._line is None:
  258. if self.lineno is None:
  259. return None
  260. self._line = linecache.getline(self.filename, self.lineno)
  261. return self._line.strip()
  262. def walk_stack(f):
  263. """Walk a stack yielding the frame and line number for each frame.
  264. This will follow f.f_back from the given frame. If no frame is given, the
  265. current stack is used. Usually used with StackSummary.extract.
  266. """
  267. if f is None:
  268. f = sys._getframe().f_back.f_back.f_back.f_back
  269. while f is not None:
  270. yield f, f.f_lineno
  271. f = f.f_back
  272. def walk_tb(tb):
  273. """Walk a traceback yielding the frame and line number for each frame.
  274. This will follow tb.tb_next (and thus is in the opposite order to
  275. walk_stack). Usually used with StackSummary.extract.
  276. """
  277. while tb is not None:
  278. yield tb.tb_frame, tb.tb_lineno
  279. tb = tb.tb_next
  280. def _walk_tb_with_full_positions(tb):
  281. # Internal version of walk_tb that yields full code positions including
  282. # end line and column information.
  283. while tb is not None:
  284. positions = _get_code_position(tb.tb_frame.f_code, tb.tb_lasti)
  285. # Yield tb_lineno when co_positions does not have a line number to
  286. # maintain behavior with walk_tb.
  287. if positions[0] is None:
  288. yield tb.tb_frame, (tb.tb_lineno, ) + positions[1:]
  289. else:
  290. yield tb.tb_frame, positions
  291. tb = tb.tb_next
  292. def _get_code_position(code, instruction_index):
  293. if instruction_index < 0:
  294. return (None, None, None, None)
  295. positions_gen = code.co_positions()
  296. return next(itertools.islice(positions_gen, instruction_index // 2, None))
  297. _RECURSIVE_CUTOFF = 3 # Also hardcoded in traceback.c.
  298. class StackSummary(list):
  299. """A list of FrameSummary objects, representing a stack of frames."""
  300. @classmethod
  301. def extract(klass, frame_gen, *, limit=None, lookup_lines=True,
  302. capture_locals=False):
  303. """Create a StackSummary from a traceback or stack object.
  304. :param frame_gen: A generator that yields (frame, lineno) tuples
  305. whose summaries are to be included in the stack.
  306. :param limit: None to include all frames or the number of frames to
  307. include.
  308. :param lookup_lines: If True, lookup lines for each frame immediately,
  309. otherwise lookup is deferred until the frame is rendered.
  310. :param capture_locals: If True, the local variables from each frame will
  311. be captured as object representations into the FrameSummary.
  312. """
  313. def extended_frame_gen():
  314. for f, lineno in frame_gen:
  315. yield f, (lineno, None, None, None)
  316. return klass._extract_from_extended_frame_gen(
  317. extended_frame_gen(), limit=limit, lookup_lines=lookup_lines,
  318. capture_locals=capture_locals)
  319. @classmethod
  320. def _extract_from_extended_frame_gen(klass, frame_gen, *, limit=None,
  321. lookup_lines=True, capture_locals=False):
  322. # Same as extract but operates on a frame generator that yields
  323. # (frame, (lineno, end_lineno, colno, end_colno)) in the stack.
  324. # Only lineno is required, the remaining fields can be None if the
  325. # information is not available.
  326. if limit is None:
  327. limit = getattr(sys, 'tracebacklimit', None)
  328. if limit is not None and limit < 0:
  329. limit = 0
  330. if limit is not None:
  331. if limit >= 0:
  332. frame_gen = itertools.islice(frame_gen, limit)
  333. else:
  334. frame_gen = collections.deque(frame_gen, maxlen=-limit)
  335. result = klass()
  336. fnames = set()
  337. for f, (lineno, end_lineno, colno, end_colno) in frame_gen:
  338. co = f.f_code
  339. filename = co.co_filename
  340. name = co.co_name
  341. fnames.add(filename)
  342. linecache.lazycache(filename, f.f_globals)
  343. # Must defer line lookups until we have called checkcache.
  344. if capture_locals:
  345. f_locals = f.f_locals
  346. else:
  347. f_locals = None
  348. result.append(FrameSummary(
  349. filename, lineno, name, lookup_line=False, locals=f_locals,
  350. end_lineno=end_lineno, colno=colno, end_colno=end_colno))
  351. for filename in fnames:
  352. linecache.checkcache(filename)
  353. # If immediate lookup was desired, trigger lookups now.
  354. if lookup_lines:
  355. for f in result:
  356. f.line
  357. return result
  358. @classmethod
  359. def from_list(klass, a_list):
  360. """
  361. Create a StackSummary object from a supplied list of
  362. FrameSummary objects or old-style list of tuples.
  363. """
  364. # While doing a fast-path check for isinstance(a_list, StackSummary) is
  365. # appealing, idlelib.run.cleanup_traceback and other similar code may
  366. # break this by making arbitrary frames plain tuples, so we need to
  367. # check on a frame by frame basis.
  368. result = StackSummary()
  369. for frame in a_list:
  370. if isinstance(frame, FrameSummary):
  371. result.append(frame)
  372. else:
  373. filename, lineno, name, line = frame
  374. result.append(FrameSummary(filename, lineno, name, line=line))
  375. return result
  376. def format_frame_summary(self, frame_summary):
  377. """Format the lines for a single FrameSummary.
  378. Returns a string representing one frame involved in the stack. This
  379. gets called for every frame to be printed in the stack summary.
  380. """
  381. row = []
  382. row.append(' File "{}", line {}, in {}\n'.format(
  383. frame_summary.filename, frame_summary.lineno, frame_summary.name))
  384. if frame_summary.line:
  385. stripped_line = frame_summary.line.strip()
  386. row.append(' {}\n'.format(stripped_line))
  387. orig_line_len = len(frame_summary._original_line)
  388. frame_line_len = len(frame_summary.line.lstrip())
  389. stripped_characters = orig_line_len - frame_line_len
  390. if (
  391. frame_summary.colno is not None
  392. and frame_summary.end_colno is not None
  393. ):
  394. start_offset = _byte_offset_to_character_offset(
  395. frame_summary._original_line, frame_summary.colno) + 1
  396. end_offset = _byte_offset_to_character_offset(
  397. frame_summary._original_line, frame_summary.end_colno) + 1
  398. anchors = None
  399. if frame_summary.lineno == frame_summary.end_lineno:
  400. with suppress(Exception):
  401. anchors = _extract_caret_anchors_from_line_segment(
  402. frame_summary._original_line[start_offset - 1:end_offset - 1]
  403. )
  404. else:
  405. end_offset = stripped_characters + len(stripped_line)
  406. # show indicators if primary char doesn't span the frame line
  407. if end_offset - start_offset < len(stripped_line) or (
  408. anchors and anchors.right_start_offset - anchors.left_end_offset > 0):
  409. row.append(' ')
  410. row.append(' ' * (start_offset - stripped_characters))
  411. if anchors:
  412. row.append(anchors.primary_char * (anchors.left_end_offset))
  413. row.append(anchors.secondary_char * (anchors.right_start_offset - anchors.left_end_offset))
  414. row.append(anchors.primary_char * (end_offset - start_offset - anchors.right_start_offset))
  415. else:
  416. row.append('^' * (end_offset - start_offset))
  417. row.append('\n')
  418. if frame_summary.locals:
  419. for name, value in sorted(frame_summary.locals.items()):
  420. row.append(' {name} = {value}\n'.format(name=name, value=value))
  421. return ''.join(row)
  422. def format(self):
  423. """Format the stack ready for printing.
  424. Returns a list of strings ready for printing. Each string in the
  425. resulting list corresponds to a single frame from the stack.
  426. Each string ends in a newline; the strings may contain internal
  427. newlines as well, for those items with source text lines.
  428. For long sequences of the same frame and line, the first few
  429. repetitions are shown, followed by a summary line stating the exact
  430. number of further repetitions.
  431. """
  432. result = []
  433. last_file = None
  434. last_line = None
  435. last_name = None
  436. count = 0
  437. for frame_summary in self:
  438. formatted_frame = self.format_frame_summary(frame_summary)
  439. if formatted_frame is None:
  440. continue
  441. if (last_file is None or last_file != frame_summary.filename or
  442. last_line is None or last_line != frame_summary.lineno or
  443. last_name is None or last_name != frame_summary.name):
  444. if count > _RECURSIVE_CUTOFF:
  445. count -= _RECURSIVE_CUTOFF
  446. result.append(
  447. f' [Previous line repeated {count} more '
  448. f'time{"s" if count > 1 else ""}]\n'
  449. )
  450. last_file = frame_summary.filename
  451. last_line = frame_summary.lineno
  452. last_name = frame_summary.name
  453. count = 0
  454. count += 1
  455. if count > _RECURSIVE_CUTOFF:
  456. continue
  457. result.append(formatted_frame)
  458. if count > _RECURSIVE_CUTOFF:
  459. count -= _RECURSIVE_CUTOFF
  460. result.append(
  461. f' [Previous line repeated {count} more '
  462. f'time{"s" if count > 1 else ""}]\n'
  463. )
  464. return result
  465. def _byte_offset_to_character_offset(str, offset):
  466. as_utf8 = str.encode('utf-8')
  467. return len(as_utf8[:offset].decode("utf-8", errors="replace"))
  468. _Anchors = collections.namedtuple(
  469. "_Anchors",
  470. [
  471. "left_end_offset",
  472. "right_start_offset",
  473. "primary_char",
  474. "secondary_char",
  475. ],
  476. defaults=["~", "^"]
  477. )
  478. def _extract_caret_anchors_from_line_segment(segment):
  479. import ast
  480. try:
  481. tree = ast.parse(segment)
  482. except SyntaxError:
  483. return None
  484. if len(tree.body) != 1:
  485. return None
  486. normalize = lambda offset: _byte_offset_to_character_offset(segment, offset)
  487. statement = tree.body[0]
  488. match statement:
  489. case ast.Expr(expr):
  490. match expr:
  491. case ast.BinOp():
  492. operator_start = normalize(expr.left.end_col_offset)
  493. operator_end = normalize(expr.right.col_offset)
  494. operator_str = segment[operator_start:operator_end]
  495. operator_offset = len(operator_str) - len(operator_str.lstrip())
  496. left_anchor = expr.left.end_col_offset + operator_offset
  497. right_anchor = left_anchor + 1
  498. if (
  499. operator_offset + 1 < len(operator_str)
  500. and not operator_str[operator_offset + 1].isspace()
  501. ):
  502. right_anchor += 1
  503. while left_anchor < len(segment) and ((ch := segment[left_anchor]).isspace() or ch in ")#"):
  504. left_anchor += 1
  505. right_anchor += 1
  506. return _Anchors(normalize(left_anchor), normalize(right_anchor))
  507. case ast.Subscript():
  508. left_anchor = normalize(expr.value.end_col_offset)
  509. right_anchor = normalize(expr.slice.end_col_offset + 1)
  510. while left_anchor < len(segment) and ((ch := segment[left_anchor]).isspace() or ch != "["):
  511. left_anchor += 1
  512. while right_anchor < len(segment) and ((ch := segment[right_anchor]).isspace() or ch != "]"):
  513. right_anchor += 1
  514. if right_anchor < len(segment):
  515. right_anchor += 1
  516. return _Anchors(left_anchor, right_anchor)
  517. return None
  518. class _ExceptionPrintContext:
  519. def __init__(self):
  520. self.seen = set()
  521. self.exception_group_depth = 0
  522. self.need_close = False
  523. def indent(self):
  524. return ' ' * (2 * self.exception_group_depth)
  525. def emit(self, text_gen, margin_char=None):
  526. if margin_char is None:
  527. margin_char = '|'
  528. indent_str = self.indent()
  529. if self.exception_group_depth:
  530. indent_str += margin_char + ' '
  531. if isinstance(text_gen, str):
  532. yield textwrap.indent(text_gen, indent_str, lambda line: True)
  533. else:
  534. for text in text_gen:
  535. yield textwrap.indent(text, indent_str, lambda line: True)
  536. class TracebackException:
  537. """An exception ready for rendering.
  538. The traceback module captures enough attributes from the original exception
  539. to this intermediary form to ensure that no references are held, while
  540. still being able to fully print or format it.
  541. max_group_width and max_group_depth control the formatting of exception
  542. groups. The depth refers to the nesting level of the group, and the width
  543. refers to the size of a single exception group's exceptions array. The
  544. formatted output is truncated when either limit is exceeded.
  545. Use `from_exception` to create TracebackException instances from exception
  546. objects, or the constructor to create TracebackException instances from
  547. individual components.
  548. - :attr:`__cause__` A TracebackException of the original *__cause__*.
  549. - :attr:`__context__` A TracebackException of the original *__context__*.
  550. - :attr:`exceptions` For exception groups - a list of TracebackException
  551. instances for the nested *exceptions*. ``None`` for other exceptions.
  552. - :attr:`__suppress_context__` The *__suppress_context__* value from the
  553. original exception.
  554. - :attr:`stack` A `StackSummary` representing the traceback.
  555. - :attr:`exc_type` The class of the original traceback.
  556. - :attr:`filename` For syntax errors - the filename where the error
  557. occurred.
  558. - :attr:`lineno` For syntax errors - the linenumber where the error
  559. occurred.
  560. - :attr:`end_lineno` For syntax errors - the end linenumber where the error
  561. occurred. Can be `None` if not present.
  562. - :attr:`text` For syntax errors - the text where the error
  563. occurred.
  564. - :attr:`offset` For syntax errors - the offset into the text where the
  565. error occurred.
  566. - :attr:`end_offset` For syntax errors - the end offset into the text where
  567. the error occurred. Can be `None` if not present.
  568. - :attr:`msg` For syntax errors - the compiler error message.
  569. """
  570. def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
  571. lookup_lines=True, capture_locals=False, compact=False,
  572. max_group_width=15, max_group_depth=10, _seen=None):
  573. # NB: we need to accept exc_traceback, exc_value, exc_traceback to
  574. # permit backwards compat with the existing API, otherwise we
  575. # need stub thunk objects just to glue it together.
  576. # Handle loops in __cause__ or __context__.
  577. is_recursive_call = _seen is not None
  578. if _seen is None:
  579. _seen = set()
  580. _seen.add(id(exc_value))
  581. self.max_group_width = max_group_width
  582. self.max_group_depth = max_group_depth
  583. self.stack = StackSummary._extract_from_extended_frame_gen(
  584. _walk_tb_with_full_positions(exc_traceback),
  585. limit=limit, lookup_lines=lookup_lines,
  586. capture_locals=capture_locals)
  587. self.exc_type = exc_type
  588. # Capture now to permit freeing resources: only complication is in the
  589. # unofficial API _format_final_exc_line
  590. self._str = _safe_string(exc_value, 'exception')
  591. self.__notes__ = getattr(exc_value, '__notes__', None)
  592. if exc_type and issubclass(exc_type, SyntaxError):
  593. # Handle SyntaxError's specially
  594. self.filename = exc_value.filename
  595. lno = exc_value.lineno
  596. self.lineno = str(lno) if lno is not None else None
  597. end_lno = exc_value.end_lineno
  598. self.end_lineno = str(end_lno) if end_lno is not None else None
  599. self.text = exc_value.text
  600. self.offset = exc_value.offset
  601. self.end_offset = exc_value.end_offset
  602. self.msg = exc_value.msg
  603. elif exc_type and issubclass(exc_type, ImportError) and \
  604. getattr(exc_value, "name_from", None) is not None:
  605. wrong_name = getattr(exc_value, "name_from", None)
  606. suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name)
  607. if suggestion:
  608. self._str += f". Did you mean: '{suggestion}'?"
  609. elif exc_type and issubclass(exc_type, (NameError, AttributeError)) and \
  610. getattr(exc_value, "name", None) is not None:
  611. wrong_name = getattr(exc_value, "name", None)
  612. suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name)
  613. if suggestion:
  614. self._str += f". Did you mean: '{suggestion}'?"
  615. if issubclass(exc_type, NameError):
  616. wrong_name = getattr(exc_value, "name", None)
  617. if wrong_name is not None and wrong_name in sys.stdlib_module_names:
  618. if suggestion:
  619. self._str += f" Or did you forget to import '{wrong_name}'"
  620. else:
  621. self._str += f". Did you forget to import '{wrong_name}'"
  622. if lookup_lines:
  623. self._load_lines()
  624. self.__suppress_context__ = \
  625. exc_value.__suppress_context__ if exc_value is not None else False
  626. # Convert __cause__ and __context__ to `TracebackExceptions`s, use a
  627. # queue to avoid recursion (only the top-level call gets _seen == None)
  628. if not is_recursive_call:
  629. queue = [(self, exc_value)]
  630. while queue:
  631. te, e = queue.pop()
  632. if (e and e.__cause__ is not None
  633. and id(e.__cause__) not in _seen):
  634. cause = TracebackException(
  635. type(e.__cause__),
  636. e.__cause__,
  637. e.__cause__.__traceback__,
  638. limit=limit,
  639. lookup_lines=lookup_lines,
  640. capture_locals=capture_locals,
  641. max_group_width=max_group_width,
  642. max_group_depth=max_group_depth,
  643. _seen=_seen)
  644. else:
  645. cause = None
  646. if compact:
  647. need_context = (cause is None and
  648. e is not None and
  649. not e.__suppress_context__)
  650. else:
  651. need_context = True
  652. if (e and e.__context__ is not None
  653. and need_context and id(e.__context__) not in _seen):
  654. context = TracebackException(
  655. type(e.__context__),
  656. e.__context__,
  657. e.__context__.__traceback__,
  658. limit=limit,
  659. lookup_lines=lookup_lines,
  660. capture_locals=capture_locals,
  661. max_group_width=max_group_width,
  662. max_group_depth=max_group_depth,
  663. _seen=_seen)
  664. else:
  665. context = None
  666. if e and isinstance(e, BaseExceptionGroup):
  667. exceptions = []
  668. for exc in e.exceptions:
  669. texc = TracebackException(
  670. type(exc),
  671. exc,
  672. exc.__traceback__,
  673. limit=limit,
  674. lookup_lines=lookup_lines,
  675. capture_locals=capture_locals,
  676. max_group_width=max_group_width,
  677. max_group_depth=max_group_depth,
  678. _seen=_seen)
  679. exceptions.append(texc)
  680. else:
  681. exceptions = None
  682. te.__cause__ = cause
  683. te.__context__ = context
  684. te.exceptions = exceptions
  685. if cause:
  686. queue.append((te.__cause__, e.__cause__))
  687. if context:
  688. queue.append((te.__context__, e.__context__))
  689. if exceptions:
  690. queue.extend(zip(te.exceptions, e.exceptions))
  691. @classmethod
  692. def from_exception(cls, exc, *args, **kwargs):
  693. """Create a TracebackException from an exception."""
  694. return cls(type(exc), exc, exc.__traceback__, *args, **kwargs)
  695. def _load_lines(self):
  696. """Private API. force all lines in the stack to be loaded."""
  697. for frame in self.stack:
  698. frame.line
  699. def __eq__(self, other):
  700. if isinstance(other, TracebackException):
  701. return self.__dict__ == other.__dict__
  702. return NotImplemented
  703. def __str__(self):
  704. return self._str
  705. def format_exception_only(self):
  706. """Format the exception part of the traceback.
  707. The return value is a generator of strings, each ending in a newline.
  708. Normally, the generator emits a single string; however, for
  709. SyntaxError exceptions, it emits several lines that (when
  710. printed) display detailed information about where the syntax
  711. error occurred.
  712. The message indicating which exception occurred is always the last
  713. string in the output.
  714. """
  715. if self.exc_type is None:
  716. yield _format_final_exc_line(None, self._str)
  717. return
  718. stype = self.exc_type.__qualname__
  719. smod = self.exc_type.__module__
  720. if smod not in ("__main__", "builtins"):
  721. if not isinstance(smod, str):
  722. smod = "<unknown>"
  723. stype = smod + '.' + stype
  724. if not issubclass(self.exc_type, SyntaxError):
  725. yield _format_final_exc_line(stype, self._str)
  726. else:
  727. yield from self._format_syntax_error(stype)
  728. if (
  729. isinstance(self.__notes__, collections.abc.Sequence)
  730. and not isinstance(self.__notes__, (str, bytes))
  731. ):
  732. for note in self.__notes__:
  733. note = _safe_string(note, 'note')
  734. yield from [l + '\n' for l in note.split('\n')]
  735. elif self.__notes__ is not None:
  736. yield "{}\n".format(_safe_string(self.__notes__, '__notes__', func=repr))
  737. def _format_syntax_error(self, stype):
  738. """Format SyntaxError exceptions (internal helper)."""
  739. # Show exactly where the problem was found.
  740. filename_suffix = ''
  741. if self.lineno is not None:
  742. yield ' File "{}", line {}\n'.format(
  743. self.filename or "<string>", self.lineno)
  744. elif self.filename is not None:
  745. filename_suffix = ' ({})'.format(self.filename)
  746. text = self.text
  747. if text is not None:
  748. # text = " foo\n"
  749. # rtext = " foo"
  750. # ltext = "foo"
  751. rtext = text.rstrip('\n')
  752. ltext = rtext.lstrip(' \n\f')
  753. spaces = len(rtext) - len(ltext)
  754. yield ' {}\n'.format(ltext)
  755. if self.offset is not None:
  756. offset = self.offset
  757. end_offset = self.end_offset if self.end_offset not in {None, 0} else offset
  758. if offset == end_offset or end_offset == -1:
  759. end_offset = offset + 1
  760. # Convert 1-based column offset to 0-based index into stripped text
  761. colno = offset - 1 - spaces
  762. end_colno = end_offset - 1 - spaces
  763. if colno >= 0:
  764. # non-space whitespace (likes tabs) must be kept for alignment
  765. caretspace = ((c if c.isspace() else ' ') for c in ltext[:colno])
  766. yield ' {}{}'.format("".join(caretspace), ('^' * (end_colno - colno) + "\n"))
  767. msg = self.msg or "<no detail available>"
  768. yield "{}: {}{}\n".format(stype, msg, filename_suffix)
  769. def format(self, *, chain=True, _ctx=None):
  770. """Format the exception.
  771. If chain is not *True*, *__cause__* and *__context__* will not be formatted.
  772. The return value is a generator of strings, each ending in a newline and
  773. some containing internal newlines. `print_exception` is a wrapper around
  774. this method which just prints the lines to a file.
  775. The message indicating which exception occurred is always the last
  776. string in the output.
  777. """
  778. if _ctx is None:
  779. _ctx = _ExceptionPrintContext()
  780. output = []
  781. exc = self
  782. if chain:
  783. while exc:
  784. if exc.__cause__ is not None:
  785. chained_msg = _cause_message
  786. chained_exc = exc.__cause__
  787. elif (exc.__context__ is not None and
  788. not exc.__suppress_context__):
  789. chained_msg = _context_message
  790. chained_exc = exc.__context__
  791. else:
  792. chained_msg = None
  793. chained_exc = None
  794. output.append((chained_msg, exc))
  795. exc = chained_exc
  796. else:
  797. output.append((None, exc))
  798. for msg, exc in reversed(output):
  799. if msg is not None:
  800. yield from _ctx.emit(msg)
  801. if exc.exceptions is None:
  802. if exc.stack:
  803. yield from _ctx.emit('Traceback (most recent call last):\n')
  804. yield from _ctx.emit(exc.stack.format())
  805. yield from _ctx.emit(exc.format_exception_only())
  806. elif _ctx.exception_group_depth > self.max_group_depth:
  807. # exception group, but depth exceeds limit
  808. yield from _ctx.emit(
  809. f"... (max_group_depth is {self.max_group_depth})\n")
  810. else:
  811. # format exception group
  812. is_toplevel = (_ctx.exception_group_depth == 0)
  813. if is_toplevel:
  814. _ctx.exception_group_depth += 1
  815. if exc.stack:
  816. yield from _ctx.emit(
  817. 'Exception Group Traceback (most recent call last):\n',
  818. margin_char = '+' if is_toplevel else None)
  819. yield from _ctx.emit(exc.stack.format())
  820. yield from _ctx.emit(exc.format_exception_only())
  821. num_excs = len(exc.exceptions)
  822. if num_excs <= self.max_group_width:
  823. n = num_excs
  824. else:
  825. n = self.max_group_width + 1
  826. _ctx.need_close = False
  827. for i in range(n):
  828. last_exc = (i == n-1)
  829. if last_exc:
  830. # The closing frame may be added by a recursive call
  831. _ctx.need_close = True
  832. if self.max_group_width is not None:
  833. truncated = (i >= self.max_group_width)
  834. else:
  835. truncated = False
  836. title = f'{i+1}' if not truncated else '...'
  837. yield (_ctx.indent() +
  838. ('+-' if i==0 else ' ') +
  839. f'+---------------- {title} ----------------\n')
  840. _ctx.exception_group_depth += 1
  841. if not truncated:
  842. yield from exc.exceptions[i].format(chain=chain, _ctx=_ctx)
  843. else:
  844. remaining = num_excs - self.max_group_width
  845. plural = 's' if remaining > 1 else ''
  846. yield from _ctx.emit(
  847. f"and {remaining} more exception{plural}\n")
  848. if last_exc and _ctx.need_close:
  849. yield (_ctx.indent() +
  850. "+------------------------------------\n")
  851. _ctx.need_close = False
  852. _ctx.exception_group_depth -= 1
  853. if is_toplevel:
  854. assert _ctx.exception_group_depth == 1
  855. _ctx.exception_group_depth = 0
  856. def print(self, *, file=None, chain=True):
  857. """Print the result of self.format(chain=chain) to 'file'."""
  858. if file is None:
  859. file = sys.stderr
  860. for line in self.format(chain=chain):
  861. print(line, file=file, end="")
  862. _MAX_CANDIDATE_ITEMS = 750
  863. _MAX_STRING_SIZE = 40
  864. _MOVE_COST = 2
  865. _CASE_COST = 1
  866. def _substitution_cost(ch_a, ch_b):
  867. if ch_a == ch_b:
  868. return 0
  869. if ch_a.lower() == ch_b.lower():
  870. return _CASE_COST
  871. return _MOVE_COST
  872. def _compute_suggestion_error(exc_value, tb, wrong_name):
  873. if wrong_name is None or not isinstance(wrong_name, str):
  874. return None
  875. if isinstance(exc_value, AttributeError):
  876. obj = exc_value.obj
  877. try:
  878. d = dir(obj)
  879. except Exception:
  880. return None
  881. elif isinstance(exc_value, ImportError):
  882. try:
  883. mod = __import__(exc_value.name)
  884. d = dir(mod)
  885. except Exception:
  886. return None
  887. else:
  888. assert isinstance(exc_value, NameError)
  889. # find most recent frame
  890. if tb is None:
  891. return None
  892. while tb.tb_next is not None:
  893. tb = tb.tb_next
  894. frame = tb.tb_frame
  895. d = (
  896. list(frame.f_locals)
  897. + list(frame.f_globals)
  898. + list(frame.f_builtins)
  899. )
  900. # Check first if we are in a method and the instance
  901. # has the wrong name as attribute
  902. if 'self' in frame.f_locals:
  903. self = frame.f_locals['self']
  904. if hasattr(self, wrong_name):
  905. return f"self.{wrong_name}"
  906. # Compute closest match
  907. if len(d) > _MAX_CANDIDATE_ITEMS:
  908. return None
  909. wrong_name_len = len(wrong_name)
  910. if wrong_name_len > _MAX_STRING_SIZE:
  911. return None
  912. best_distance = wrong_name_len
  913. suggestion = None
  914. for possible_name in d:
  915. if possible_name == wrong_name:
  916. # A missing attribute is "found". Don't suggest it (see GH-88821).
  917. continue
  918. # No more than 1/3 of the involved characters should need changed.
  919. max_distance = (len(possible_name) + wrong_name_len + 3) * _MOVE_COST // 6
  920. # Don't take matches we've already beaten.
  921. max_distance = min(max_distance, best_distance - 1)
  922. current_distance = _levenshtein_distance(wrong_name, possible_name, max_distance)
  923. if current_distance > max_distance:
  924. continue
  925. if not suggestion or current_distance < best_distance:
  926. suggestion = possible_name
  927. best_distance = current_distance
  928. return suggestion
  929. def _levenshtein_distance(a, b, max_cost):
  930. # A Python implementation of Python/suggestions.c:levenshtein_distance.
  931. # Both strings are the same
  932. if a == b:
  933. return 0
  934. # Trim away common affixes
  935. pre = 0
  936. while a[pre:] and b[pre:] and a[pre] == b[pre]:
  937. pre += 1
  938. a = a[pre:]
  939. b = b[pre:]
  940. post = 0
  941. while a[:post or None] and b[:post or None] and a[post-1] == b[post-1]:
  942. post -= 1
  943. a = a[:post or None]
  944. b = b[:post or None]
  945. if not a or not b:
  946. return _MOVE_COST * (len(a) + len(b))
  947. if len(a) > _MAX_STRING_SIZE or len(b) > _MAX_STRING_SIZE:
  948. return max_cost + 1
  949. # Prefer shorter buffer
  950. if len(b) < len(a):
  951. a, b = b, a
  952. # Quick fail when a match is impossible
  953. if (len(b) - len(a)) * _MOVE_COST > max_cost:
  954. return max_cost + 1
  955. # Instead of producing the whole traditional len(a)-by-len(b)
  956. # matrix, we can update just one row in place.
  957. # Initialize the buffer row
  958. row = list(range(_MOVE_COST, _MOVE_COST * (len(a) + 1), _MOVE_COST))
  959. result = 0
  960. for bindex in range(len(b)):
  961. bchar = b[bindex]
  962. distance = result = bindex * _MOVE_COST
  963. minimum = sys.maxsize
  964. for index in range(len(a)):
  965. # 1) Previous distance in this row is cost(b[:b_index], a[:index])
  966. substitute = distance + _substitution_cost(bchar, a[index])
  967. # 2) cost(b[:b_index], a[:index+1]) from previous row
  968. distance = row[index]
  969. # 3) existing result is cost(b[:b_index+1], a[index])
  970. insert_delete = min(result, distance) + _MOVE_COST
  971. result = min(insert_delete, substitute)
  972. # cost(b[:b_index+1], a[:index+1])
  973. row[index] = result
  974. if result < minimum:
  975. minimum = result
  976. if minimum > max_cost:
  977. # Everything in this row is too big, so bail early.
  978. return max_cost + 1
  979. return result