traceback.py 45 KB

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