1from __future__
import absolute_import
7from dataclasses
import dataclass, field
8from traceback
import walk_tb
9from types
import ModuleType, TracebackType
30from ._loop
import loop_last
31from .columns
import Columns
32from .console
import Console, ConsoleOptions, ConsoleRenderable, RenderResult, group
33from .constrain
import Constrain
34from .highlighter
import RegexHighlighter, ReprHighlighter
35from .panel
import Panel
36from .scope
import render_scope
37from .style
import Style
38from .syntax
import Syntax
40from .theme
import Theme
50 console: Optional[Console] =
None,
51 width: Optional[int] = 100,
53 theme: Optional[str] =
None,
54 word_wrap: bool =
False,
55 show_locals: bool =
False,
56 locals_max_length: int = LOCALS_MAX_LENGTH,
57 locals_max_string: int = LOCALS_MAX_STRING,
58 locals_hide_dunder: bool =
True,
59 locals_hide_sunder: Optional[bool] =
None,
60 indent_guides: bool =
True,
61 suppress: Iterable[Union[str, ModuleType]] = (),
62 max_frames: int = 100,
63) -> Callable[[Type[BaseException], BaseException, Optional[TracebackType]], Any]:
64 """Install a rich traceback handler.
66 Once installed, any tracebacks will be printed with syntax highlighting and rich formatting.
70 console (Optional[Console], optional): Console to write exception to. Default uses internal Console instance.
71 width (Optional[int], optional): Width (in characters) of traceback. Defaults to 100.
72 extra_lines (int, optional): Extra lines of code. Defaults to 3.
73 theme (Optional[str], optional): Pygments theme to use in traceback. Defaults to ``None`` which will pick
74 a theme appropriate for the platform.
75 word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
76 show_locals (bool, optional): Enable display of local variables. Defaults to False.
77 locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
79 locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
80 locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
81 locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
82 indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
83 suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
86 Callable: The previous exception handler that was replaced.
89 traceback_console =
Console(stderr=
True)
if console
is None else console
91 locals_hide_sunder = (
94 else locals_hide_sunder
98 type_: Type[BaseException],
100 traceback: Optional[TracebackType],
108 extra_lines=extra_lines,
111 show_locals=show_locals,
112 locals_max_length=locals_max_length,
113 locals_max_string=locals_max_string,
114 locals_hide_dunder=locals_hide_dunder,
115 locals_hide_sunder=bool(locals_hide_sunder),
116 indent_guides=indent_guides,
118 max_frames=max_frames,
127 """wrap the default ip.showtraceback to store info for ip._showtraceback"""
133 *args: Any, is_syntax: bool =
False, **kwargs: Any
135 """Internally called traceback from ip._showtraceback"""
140 tb: Optional[TracebackType] =
None if is_syntax
else exc_tuple[2]
143 compiled =
tb_data.get(
"running_compiled_code",
False)
144 tb_offset =
tb_data.get(
"tb_offset", 1
if compiled
else 0)
146 for _
in range(tb_offset):
160 *args, is_syntax=
True, **kwargs
172 return old_excepthook
197 syntax_error: Optional[_SyntaxError] =
None
198 is_cause: bool =
False
199 frames: List[Frame] = field(default_factory=list)
208 highlights = [
r"(?P<dim>.*/)(?P<bold>.+)"]
212 """A Console renderable that renders a traceback.
215 trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses
217 width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
218 extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
219 theme (str, optional): Override pygments theme used in traceback.
220 word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
221 show_locals (bool, optional): Enable display of local variables. Defaults to False.
222 indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
223 locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
225 locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
226 locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
227 locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
228 suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
229 max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
243 trace: Optional[Trace] =
None,
245 width: Optional[int] = 100,
246 extra_lines: int = 3,
247 theme: Optional[str] =
None,
248 word_wrap: bool =
False,
249 show_locals: bool =
False,
250 locals_max_length: int = LOCALS_MAX_LENGTH,
251 locals_max_string: int = LOCALS_MAX_STRING,
252 locals_hide_dunder: bool =
True,
253 locals_hide_sunder: bool =
False,
254 indent_guides: bool =
True,
255 suppress: Iterable[Union[str, ModuleType]] = (),
256 max_frames: int = 100,
260 if exc_type
is None or exc_value
is None or traceback
is None:
262 "Value for 'trace' required if not called in except: block"
265 exc_type, exc_value, traceback, show_locals=show_locals
279 self.suppress: Sequence[str] = []
280 for suppress_entity
in suppress:
284 ), f
"{suppress_entity!r} must be a module with '__file__' attribute"
287 path = suppress_entity
289 self.suppress.append(path)
290 self.
max_frames = max(4, max_frames)
if max_frames > 0
else 0
296 exc_value: BaseException,
297 traceback: Optional[TracebackType],
299 width: Optional[int] = 100,
300 extra_lines: int = 3,
301 theme: Optional[str] =
None,
302 word_wrap: bool =
False,
303 show_locals: bool =
False,
304 locals_max_length: int = LOCALS_MAX_LENGTH,
305 locals_max_string: int = LOCALS_MAX_STRING,
306 locals_hide_dunder: bool =
True,
307 locals_hide_sunder: bool =
False,
308 indent_guides: bool =
True,
309 suppress: Iterable[Union[str, ModuleType]] = (),
310 max_frames: int = 100,
312 """Create a traceback from exception info
315 exc_type (Type[BaseException]): Exception type.
316 exc_value (BaseException): Exception value.
317 traceback (TracebackType): Python Traceback object.
318 width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
319 extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
320 theme (str, optional): Override pygments theme used in traceback.
321 word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
322 show_locals (bool, optional): Enable display of local variables. Defaults to False.
323 indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
324 locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
326 locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
327 locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
328 locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
329 suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
330 max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
333 Traceback: A Traceback instance that may be printed.
339 show_locals=show_locals,
340 locals_max_length=locals_max_length,
341 locals_max_string=locals_max_string,
342 locals_hide_dunder=locals_hide_dunder,
343 locals_hide_sunder=locals_hide_sunder,
349 extra_lines=extra_lines,
352 show_locals=show_locals,
353 indent_guides=indent_guides,
354 locals_max_length=locals_max_length,
355 locals_max_string=locals_max_string,
356 locals_hide_dunder=locals_hide_dunder,
357 locals_hide_sunder=locals_hide_sunder,
359 max_frames=max_frames,
365 exc_type: Type[BaseException],
366 exc_value: BaseException,
367 traceback: Optional[TracebackType],
369 show_locals: bool =
False,
370 locals_max_length: int = LOCALS_MAX_LENGTH,
371 locals_max_string: int = LOCALS_MAX_STRING,
372 locals_hide_dunder: bool =
True,
373 locals_hide_sunder: bool =
False,
375 """Extract traceback information.
378 exc_type (Type[BaseException]): Exception type.
379 exc_value (BaseException): Exception value.
380 traceback (TracebackType): Python Traceback object.
381 show_locals (bool, optional): Enable display of local variables. Defaults to False.
382 locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
384 locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
385 locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
386 locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
389 Trace: A Trace instance which you can use to construct a `Traceback`.
392 stacks: List[Stack] = []
398 """Don't allow exceptions from __str__ to propagate."""
402 return "<exception str() failed>"
424 iter_locals: Iterable[Tuple[str, object]]
425 ) -> Iterable[Tuple[str, object]]:
426 """Extract locals from an iterator of key pairs."""
427 if not (locals_hide_dunder
or locals_hide_sunder):
428 yield from iter_locals
430 for key, value
in iter_locals:
437 for frame_summary, line_no
in walk_tb(traceback):
446 filename=filename
or "?",
452 max_length=locals_max_length,
453 max_string=locals_max_string,
464 cause =
getattr(exc_value,
"__cause__",
None)
475 if cause
and not getattr(exc_value,
"__suppress_context__",
False):
484 trace =
Trace(stacks=stacks)
488 self, console: Console, options: ConsoleOptions
494 traceback_theme =
Theme(
519 stack_renderable: ConsoleRenderable =
Panel(
521 title=
"[traceback.title]Traceback [dim](most recent call last)",
522 style=background_style,
523 border_style=
"traceback.border",
529 yield stack_renderable
535 style=background_style,
536 border_style=
"traceback.border.syntax_error",
544 (f
"{stack.exc_type}: ",
"traceback.exc_type"),
549 (f
"{stack.exc_type}: ",
"traceback.exc_type"),
553 yield Text.assemble((f
"{stack.exc_type}",
"traceback.exc_type"))
558 "\n[i]The above exception was the direct cause of the following exception:\n",
562 "\n[i]During handling of the above exception, another exception occurred:\n",
572 (f
" {syntax_error.filename}",
"pygments.string"),
573 (
":",
"pygments.text"),
575 style=
"pygments.text",
583 "\n" +
" " * offset +
"[traceback.offset]▲[/]",
584 style=
"pygments.text",
586 yield syntax_error_text
596 first_line = code[:new_line_index]
if new_line_index != -1
else code
600 return cls.
LEXERS.get(ext)
or guess_lexer_for_filename(filename, code).name
601 except ClassNotFound:
610 """Read files, and cache results on filename.
613 filename (str): Filename to read
616 str: Contents of file
620 def render_locals(frame: Frame) -> Iterable[ConsoleRenderable]:
630 exclude_frames: Optional[range] =
None
632 exclude_frames =
range(
640 if exclude_frames
and frame_index
in exclude_frames:
645 assert exclude_frames
is not None
647 f
"\n... {len(exclude_frames)} frames hidden ...",
649 style=
"traceback.error",
653 first = frame_index == 0
660 (
":",
"pygments.text"),
664 style=
"pygments.text",
670 (
":",
"pygments.text"),
672 style=
"pygments.text",
704 except Exception
as error:
706 (f
"\n{error}",
"traceback.error"),
722if __name__ ==
"__main__":
724 from .console
import Console
729 def bar(a: Any) ->
None:
734 _rich_traceback_guard =
True
738 "Vladimir Harkonnen",
742 "atomic_types": (
None,
False,
True),
"Traceback" from_exception(cls, Type[Any] exc_type, BaseException exc_value, Optional[TracebackType] traceback, *Optional[int] width=100, int extra_lines=3, Optional[str] theme=None, bool word_wrap=False, bool show_locals=False, int locals_max_length=LOCALS_MAX_LENGTH, int locals_max_string=LOCALS_MAX_STRING, bool locals_hide_dunder=True, bool locals_hide_sunder=False, bool indent_guides=True, Iterable[Union[str, ModuleType]] suppress=(), int max_frames=100)
RenderResult _render_syntax_error(self, _SyntaxError syntax_error)
str _guess_lexer(cls, str filename, str code)
__init__(self, Optional[Trace] trace=None, *Optional[int] width=100, int extra_lines=3, Optional[str] theme=None, bool word_wrap=False, bool show_locals=False, int locals_max_length=LOCALS_MAX_LENGTH, int locals_max_string=LOCALS_MAX_STRING, bool locals_hide_dunder=True, bool locals_hide_sunder=False, bool indent_guides=True, Iterable[Union[str, ModuleType]] suppress=(), int max_frames=100)
RenderResult __rich_console__(self, Console console, ConsoleOptions options)
Trace extract(cls, Type[BaseException] exc_type, BaseException exc_value, Optional[TracebackType] traceback, *bool show_locals=False, int locals_max_length=LOCALS_MAX_LENGTH, int locals_max_string=LOCALS_MAX_STRING, bool locals_hide_dunder=True, bool locals_hide_sunder=False)
RenderResult _render_stack(self, Stack stack)