traceback.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. from __future__ import absolute_import
  2. import os
  3. import platform
  4. import sys
  5. from dataclasses import dataclass, field
  6. from traceback import walk_tb
  7. from types import ModuleType, TracebackType
  8. from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Type, Union
  9. from pip._vendor.pygments.lexers import guess_lexer_for_filename
  10. from pip._vendor.pygments.token import Comment, Keyword, Name, Number, Operator, String
  11. from pip._vendor.pygments.token import Text as TextToken
  12. from pip._vendor.pygments.token import Token
  13. from . import pretty
  14. from ._loop import loop_first, loop_last
  15. from .columns import Columns
  16. from .console import Console, ConsoleOptions, ConsoleRenderable, RenderResult, group
  17. from .constrain import Constrain
  18. from .highlighter import RegexHighlighter, ReprHighlighter
  19. from .panel import Panel
  20. from .scope import render_scope
  21. from .style import Style
  22. from .syntax import Syntax
  23. from .text import Text
  24. from .theme import Theme
  25. WINDOWS = platform.system() == "Windows"
  26. LOCALS_MAX_LENGTH = 10
  27. LOCALS_MAX_STRING = 80
  28. def install(
  29. *,
  30. console: Optional[Console] = None,
  31. width: Optional[int] = 100,
  32. extra_lines: int = 3,
  33. theme: Optional[str] = None,
  34. word_wrap: bool = False,
  35. show_locals: bool = False,
  36. indent_guides: bool = True,
  37. suppress: Iterable[Union[str, ModuleType]] = (),
  38. max_frames: int = 100,
  39. ) -> Callable[[Type[BaseException], BaseException, Optional[TracebackType]], Any]:
  40. """Install a rich traceback handler.
  41. Once installed, any tracebacks will be printed with syntax highlighting and rich formatting.
  42. Args:
  43. console (Optional[Console], optional): Console to write exception to. Default uses internal Console instance.
  44. width (Optional[int], optional): Width (in characters) of traceback. Defaults to 100.
  45. extra_lines (int, optional): Extra lines of code. Defaults to 3.
  46. theme (Optional[str], optional): Pygments theme to use in traceback. Defaults to ``None`` which will pick
  47. a theme appropriate for the platform.
  48. word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
  49. show_locals (bool, optional): Enable display of local variables. Defaults to False.
  50. indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
  51. suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
  52. Returns:
  53. Callable: The previous exception handler that was replaced.
  54. """
  55. traceback_console = Console(file=sys.stderr) if console is None else console
  56. def excepthook(
  57. type_: Type[BaseException],
  58. value: BaseException,
  59. traceback: Optional[TracebackType],
  60. ) -> None:
  61. traceback_console.print(
  62. Traceback.from_exception(
  63. type_,
  64. value,
  65. traceback,
  66. width=width,
  67. extra_lines=extra_lines,
  68. theme=theme,
  69. word_wrap=word_wrap,
  70. show_locals=show_locals,
  71. indent_guides=indent_guides,
  72. suppress=suppress,
  73. max_frames=max_frames,
  74. )
  75. )
  76. def ipy_excepthook_closure(ip: Any) -> None: # pragma: no cover
  77. tb_data = {} # store information about showtraceback call
  78. default_showtraceback = ip.showtraceback # keep reference of default traceback
  79. def ipy_show_traceback(*args: Any, **kwargs: Any) -> None:
  80. """wrap the default ip.showtraceback to store info for ip._showtraceback"""
  81. nonlocal tb_data
  82. tb_data = kwargs
  83. default_showtraceback(*args, **kwargs)
  84. def ipy_display_traceback(
  85. *args: Any, is_syntax: bool = False, **kwargs: Any
  86. ) -> None:
  87. """Internally called traceback from ip._showtraceback"""
  88. nonlocal tb_data
  89. exc_tuple = ip._get_exc_info()
  90. # do not display trace on syntax error
  91. tb: Optional[TracebackType] = None if is_syntax else exc_tuple[2]
  92. # determine correct tb_offset
  93. compiled = tb_data.get("running_compiled_code", False)
  94. tb_offset = tb_data.get("tb_offset", 1 if compiled else 0)
  95. # remove ipython internal frames from trace with tb_offset
  96. for _ in range(tb_offset):
  97. if tb is None:
  98. break
  99. tb = tb.tb_next
  100. excepthook(exc_tuple[0], exc_tuple[1], tb)
  101. tb_data = {} # clear data upon usage
  102. # replace _showtraceback instead of showtraceback to allow ipython features such as debugging to work
  103. # this is also what the ipython docs recommends to modify when subclassing InteractiveShell
  104. ip._showtraceback = ipy_display_traceback
  105. # add wrapper to capture tb_data
  106. ip.showtraceback = ipy_show_traceback
  107. ip.showsyntaxerror = lambda *args, **kwargs: ipy_display_traceback(
  108. *args, is_syntax=True, **kwargs
  109. )
  110. try: # pragma: no cover
  111. # if within ipython, use customized traceback
  112. ip = get_ipython() # type: ignore
  113. ipy_excepthook_closure(ip)
  114. return sys.excepthook
  115. except Exception:
  116. # otherwise use default system hook
  117. old_excepthook = sys.excepthook
  118. sys.excepthook = excepthook
  119. return old_excepthook
  120. @dataclass
  121. class Frame:
  122. filename: str
  123. lineno: int
  124. name: str
  125. line: str = ""
  126. locals: Optional[Dict[str, pretty.Node]] = None
  127. @dataclass
  128. class _SyntaxError:
  129. offset: int
  130. filename: str
  131. line: str
  132. lineno: int
  133. msg: str
  134. @dataclass
  135. class Stack:
  136. exc_type: str
  137. exc_value: str
  138. syntax_error: Optional[_SyntaxError] = None
  139. is_cause: bool = False
  140. frames: List[Frame] = field(default_factory=list)
  141. @dataclass
  142. class Trace:
  143. stacks: List[Stack]
  144. class PathHighlighter(RegexHighlighter):
  145. highlights = [r"(?P<dim>.*/)(?P<bold>.+)"]
  146. class Traceback:
  147. """A Console renderable that renders a traceback.
  148. Args:
  149. trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses
  150. the last exception.
  151. width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
  152. extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
  153. theme (str, optional): Override pygments theme used in traceback.
  154. word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
  155. show_locals (bool, optional): Enable display of local variables. Defaults to False.
  156. indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
  157. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
  158. Defaults to 10.
  159. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
  160. suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
  161. max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
  162. """
  163. LEXERS = {
  164. "": "text",
  165. ".py": "python",
  166. ".pxd": "cython",
  167. ".pyx": "cython",
  168. ".pxi": "pyrex",
  169. }
  170. def __init__(
  171. self,
  172. trace: Optional[Trace] = None,
  173. width: Optional[int] = 100,
  174. extra_lines: int = 3,
  175. theme: Optional[str] = None,
  176. word_wrap: bool = False,
  177. show_locals: bool = False,
  178. indent_guides: bool = True,
  179. locals_max_length: int = LOCALS_MAX_LENGTH,
  180. locals_max_string: int = LOCALS_MAX_STRING,
  181. suppress: Iterable[Union[str, ModuleType]] = (),
  182. max_frames: int = 100,
  183. ):
  184. if trace is None:
  185. exc_type, exc_value, traceback = sys.exc_info()
  186. if exc_type is None or exc_value is None or traceback is None:
  187. raise ValueError(
  188. "Value for 'trace' required if not called in except: block"
  189. )
  190. trace = self.extract(
  191. exc_type, exc_value, traceback, show_locals=show_locals
  192. )
  193. self.trace = trace
  194. self.width = width
  195. self.extra_lines = extra_lines
  196. self.theme = Syntax.get_theme(theme or "ansi_dark")
  197. self.word_wrap = word_wrap
  198. self.show_locals = show_locals
  199. self.indent_guides = indent_guides
  200. self.locals_max_length = locals_max_length
  201. self.locals_max_string = locals_max_string
  202. self.suppress: Sequence[str] = []
  203. for suppress_entity in suppress:
  204. if not isinstance(suppress_entity, str):
  205. assert (
  206. suppress_entity.__file__ is not None
  207. ), f"{suppress_entity!r} must be a module with '__file__' attribute"
  208. path = os.path.dirname(suppress_entity.__file__)
  209. else:
  210. path = suppress_entity
  211. path = os.path.normpath(os.path.abspath(path))
  212. self.suppress.append(path)
  213. self.max_frames = max(4, max_frames) if max_frames > 0 else 0
  214. @classmethod
  215. def from_exception(
  216. cls,
  217. exc_type: Type[Any],
  218. exc_value: BaseException,
  219. traceback: Optional[TracebackType],
  220. width: Optional[int] = 100,
  221. extra_lines: int = 3,
  222. theme: Optional[str] = None,
  223. word_wrap: bool = False,
  224. show_locals: bool = False,
  225. indent_guides: bool = True,
  226. locals_max_length: int = LOCALS_MAX_LENGTH,
  227. locals_max_string: int = LOCALS_MAX_STRING,
  228. suppress: Iterable[Union[str, ModuleType]] = (),
  229. max_frames: int = 100,
  230. ) -> "Traceback":
  231. """Create a traceback from exception info
  232. Args:
  233. exc_type (Type[BaseException]): Exception type.
  234. exc_value (BaseException): Exception value.
  235. traceback (TracebackType): Python Traceback object.
  236. width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
  237. extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
  238. theme (str, optional): Override pygments theme used in traceback.
  239. word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
  240. show_locals (bool, optional): Enable display of local variables. Defaults to False.
  241. indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
  242. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
  243. Defaults to 10.
  244. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
  245. suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
  246. max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
  247. Returns:
  248. Traceback: A Traceback instance that may be printed.
  249. """
  250. rich_traceback = cls.extract(
  251. exc_type, exc_value, traceback, show_locals=show_locals
  252. )
  253. return cls(
  254. rich_traceback,
  255. width=width,
  256. extra_lines=extra_lines,
  257. theme=theme,
  258. word_wrap=word_wrap,
  259. show_locals=show_locals,
  260. indent_guides=indent_guides,
  261. locals_max_length=locals_max_length,
  262. locals_max_string=locals_max_string,
  263. suppress=suppress,
  264. max_frames=max_frames,
  265. )
  266. @classmethod
  267. def extract(
  268. cls,
  269. exc_type: Type[BaseException],
  270. exc_value: BaseException,
  271. traceback: Optional[TracebackType],
  272. show_locals: bool = False,
  273. locals_max_length: int = LOCALS_MAX_LENGTH,
  274. locals_max_string: int = LOCALS_MAX_STRING,
  275. ) -> Trace:
  276. """Extract traceback information.
  277. Args:
  278. exc_type (Type[BaseException]): Exception type.
  279. exc_value (BaseException): Exception value.
  280. traceback (TracebackType): Python Traceback object.
  281. show_locals (bool, optional): Enable display of local variables. Defaults to False.
  282. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
  283. Defaults to 10.
  284. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
  285. Returns:
  286. Trace: A Trace instance which you can use to construct a `Traceback`.
  287. """
  288. stacks: List[Stack] = []
  289. is_cause = False
  290. from pip._vendor.rich import _IMPORT_CWD
  291. def safe_str(_object: Any) -> str:
  292. """Don't allow exceptions from __str__ to propegate."""
  293. try:
  294. return str(_object)
  295. except Exception:
  296. return "<exception str() failed>"
  297. while True:
  298. stack = Stack(
  299. exc_type=safe_str(exc_type.__name__),
  300. exc_value=safe_str(exc_value),
  301. is_cause=is_cause,
  302. )
  303. if isinstance(exc_value, SyntaxError):
  304. stack.syntax_error = _SyntaxError(
  305. offset=exc_value.offset or 0,
  306. filename=exc_value.filename or "?",
  307. lineno=exc_value.lineno or 0,
  308. line=exc_value.text or "",
  309. msg=exc_value.msg,
  310. )
  311. stacks.append(stack)
  312. append = stack.frames.append
  313. for frame_summary, line_no in walk_tb(traceback):
  314. filename = frame_summary.f_code.co_filename
  315. if filename and not filename.startswith("<"):
  316. if not os.path.isabs(filename):
  317. filename = os.path.join(_IMPORT_CWD, filename)
  318. frame = Frame(
  319. filename=filename or "?",
  320. lineno=line_no,
  321. name=frame_summary.f_code.co_name,
  322. locals={
  323. key: pretty.traverse(
  324. value,
  325. max_length=locals_max_length,
  326. max_string=locals_max_string,
  327. )
  328. for key, value in frame_summary.f_locals.items()
  329. }
  330. if show_locals
  331. else None,
  332. )
  333. append(frame)
  334. if "_rich_traceback_guard" in frame_summary.f_locals:
  335. del stack.frames[:]
  336. cause = getattr(exc_value, "__cause__", None)
  337. if cause and cause.__traceback__:
  338. exc_type = cause.__class__
  339. exc_value = cause
  340. traceback = cause.__traceback__
  341. if traceback:
  342. is_cause = True
  343. continue
  344. cause = exc_value.__context__
  345. if (
  346. cause
  347. and cause.__traceback__
  348. and not getattr(exc_value, "__suppress_context__", False)
  349. ):
  350. exc_type = cause.__class__
  351. exc_value = cause
  352. traceback = cause.__traceback__
  353. if traceback:
  354. is_cause = False
  355. continue
  356. # No cover, code is reached but coverage doesn't recognize it.
  357. break # pragma: no cover
  358. trace = Trace(stacks=stacks)
  359. return trace
  360. def __rich_console__(
  361. self, console: Console, options: ConsoleOptions
  362. ) -> RenderResult:
  363. theme = self.theme
  364. background_style = theme.get_background_style()
  365. token_style = theme.get_style_for_token
  366. traceback_theme = Theme(
  367. {
  368. "pretty": token_style(TextToken),
  369. "pygments.text": token_style(Token),
  370. "pygments.string": token_style(String),
  371. "pygments.function": token_style(Name.Function),
  372. "pygments.number": token_style(Number),
  373. "repr.indent": token_style(Comment) + Style(dim=True),
  374. "repr.str": token_style(String),
  375. "repr.brace": token_style(TextToken) + Style(bold=True),
  376. "repr.number": token_style(Number),
  377. "repr.bool_true": token_style(Keyword.Constant),
  378. "repr.bool_false": token_style(Keyword.Constant),
  379. "repr.none": token_style(Keyword.Constant),
  380. "scope.border": token_style(String.Delimiter),
  381. "scope.equals": token_style(Operator),
  382. "scope.key": token_style(Name),
  383. "scope.key.special": token_style(Name.Constant) + Style(dim=True),
  384. },
  385. inherit=False,
  386. )
  387. highlighter = ReprHighlighter()
  388. for last, stack in loop_last(reversed(self.trace.stacks)):
  389. if stack.frames:
  390. stack_renderable: ConsoleRenderable = Panel(
  391. self._render_stack(stack),
  392. title="[traceback.title]Traceback [dim](most recent call last)",
  393. style=background_style,
  394. border_style="traceback.border",
  395. expand=True,
  396. padding=(0, 1),
  397. )
  398. stack_renderable = Constrain(stack_renderable, self.width)
  399. with console.use_theme(traceback_theme):
  400. yield stack_renderable
  401. if stack.syntax_error is not None:
  402. with console.use_theme(traceback_theme):
  403. yield Constrain(
  404. Panel(
  405. self._render_syntax_error(stack.syntax_error),
  406. style=background_style,
  407. border_style="traceback.border.syntax_error",
  408. expand=True,
  409. padding=(0, 1),
  410. width=self.width,
  411. ),
  412. self.width,
  413. )
  414. yield Text.assemble(
  415. (f"{stack.exc_type}: ", "traceback.exc_type"),
  416. highlighter(stack.syntax_error.msg),
  417. )
  418. elif stack.exc_value:
  419. yield Text.assemble(
  420. (f"{stack.exc_type}: ", "traceback.exc_type"),
  421. highlighter(stack.exc_value),
  422. )
  423. else:
  424. yield Text.assemble((f"{stack.exc_type}", "traceback.exc_type"))
  425. if not last:
  426. if stack.is_cause:
  427. yield Text.from_markup(
  428. "\n[i]The above exception was the direct cause of the following exception:\n",
  429. )
  430. else:
  431. yield Text.from_markup(
  432. "\n[i]During handling of the above exception, another exception occurred:\n",
  433. )
  434. @group()
  435. def _render_syntax_error(self, syntax_error: _SyntaxError) -> RenderResult:
  436. highlighter = ReprHighlighter()
  437. path_highlighter = PathHighlighter()
  438. if syntax_error.filename != "<stdin>":
  439. text = Text.assemble(
  440. (f" {syntax_error.filename}", "pygments.string"),
  441. (":", "pygments.text"),
  442. (str(syntax_error.lineno), "pygments.number"),
  443. style="pygments.text",
  444. )
  445. yield path_highlighter(text)
  446. syntax_error_text = highlighter(syntax_error.line.rstrip())
  447. syntax_error_text.no_wrap = True
  448. offset = min(syntax_error.offset - 1, len(syntax_error_text))
  449. syntax_error_text.stylize("bold underline", offset, offset)
  450. syntax_error_text += Text.from_markup(
  451. "\n" + " " * offset + "[traceback.offset]▲[/]",
  452. style="pygments.text",
  453. )
  454. yield syntax_error_text
  455. @classmethod
  456. def _guess_lexer(cls, filename: str, code: str) -> str:
  457. ext = os.path.splitext(filename)[-1]
  458. if not ext:
  459. # No extension, look at first line to see if it is a hashbang
  460. # Note, this is an educated guess and not a guarantee
  461. # If it fails, the only downside is that the code is highlighted strangely
  462. new_line_index = code.index("\n")
  463. first_line = code[:new_line_index] if new_line_index != -1 else code
  464. if first_line.startswith("#!") and "python" in first_line.lower():
  465. return "python"
  466. lexer_name = (
  467. cls.LEXERS.get(ext) or guess_lexer_for_filename(filename, code).name
  468. )
  469. return lexer_name
  470. @group()
  471. def _render_stack(self, stack: Stack) -> RenderResult:
  472. path_highlighter = PathHighlighter()
  473. theme = self.theme
  474. code_cache: Dict[str, str] = {}
  475. def read_code(filename: str) -> str:
  476. """Read files, and cache results on filename.
  477. Args:
  478. filename (str): Filename to read
  479. Returns:
  480. str: Contents of file
  481. """
  482. code = code_cache.get(filename)
  483. if code is None:
  484. with open(
  485. filename, "rt", encoding="utf-8", errors="replace"
  486. ) as code_file:
  487. code = code_file.read()
  488. code_cache[filename] = code
  489. return code
  490. def render_locals(frame: Frame) -> Iterable[ConsoleRenderable]:
  491. if frame.locals:
  492. yield render_scope(
  493. frame.locals,
  494. title="locals",
  495. indent_guides=self.indent_guides,
  496. max_length=self.locals_max_length,
  497. max_string=self.locals_max_string,
  498. )
  499. exclude_frames: Optional[range] = None
  500. if self.max_frames != 0:
  501. exclude_frames = range(
  502. self.max_frames // 2,
  503. len(stack.frames) - self.max_frames // 2,
  504. )
  505. excluded = False
  506. for frame_index, frame in enumerate(stack.frames):
  507. if exclude_frames and frame_index in exclude_frames:
  508. excluded = True
  509. continue
  510. if excluded:
  511. assert exclude_frames is not None
  512. yield Text(
  513. f"\n... {len(exclude_frames)} frames hidden ...",
  514. justify="center",
  515. style="traceback.error",
  516. )
  517. excluded = False
  518. first = frame_index == 1
  519. frame_filename = frame.filename
  520. suppressed = any(frame_filename.startswith(path) for path in self.suppress)
  521. text = Text.assemble(
  522. path_highlighter(Text(frame.filename, style="pygments.string")),
  523. (":", "pygments.text"),
  524. (str(frame.lineno), "pygments.number"),
  525. " in ",
  526. (frame.name, "pygments.function"),
  527. style="pygments.text",
  528. )
  529. if not frame.filename.startswith("<") and not first:
  530. yield ""
  531. yield text
  532. if frame.filename.startswith("<"):
  533. yield from render_locals(frame)
  534. continue
  535. if not suppressed:
  536. try:
  537. code = read_code(frame.filename)
  538. lexer_name = self._guess_lexer(frame.filename, code)
  539. syntax = Syntax(
  540. code,
  541. lexer_name,
  542. theme=theme,
  543. line_numbers=True,
  544. line_range=(
  545. frame.lineno - self.extra_lines,
  546. frame.lineno + self.extra_lines,
  547. ),
  548. highlight_lines={frame.lineno},
  549. word_wrap=self.word_wrap,
  550. code_width=88,
  551. indent_guides=self.indent_guides,
  552. dedent=False,
  553. )
  554. yield ""
  555. except Exception as error:
  556. yield Text.assemble(
  557. (f"\n{error}", "traceback.error"),
  558. )
  559. else:
  560. yield (
  561. Columns(
  562. [
  563. syntax,
  564. *render_locals(frame),
  565. ],
  566. padding=1,
  567. )
  568. if frame.locals
  569. else syntax
  570. )
  571. if __name__ == "__main__": # pragma: no cover
  572. from .console import Console
  573. console = Console()
  574. import sys
  575. def bar(a: Any) -> None: # 这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑
  576. one = 1
  577. print(one / a)
  578. def foo(a: Any) -> None:
  579. _rich_traceback_guard = True
  580. zed = {
  581. "characters": {
  582. "Paul Atreides",
  583. "Vladimir Harkonnen",
  584. "Thufir Hawat",
  585. "Duncan Idaho",
  586. },
  587. "atomic_types": (None, False, True),
  588. }
  589. bar(a)
  590. def error() -> None:
  591. try:
  592. try:
  593. foo(0)
  594. except:
  595. slfkjsldkfj # type: ignore
  596. except:
  597. console.print_exception(show_locals=True)
  598. error()