Skip to content
Myr

✨ Add pretty error tracebacks for user errors and support for Rich (#412)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sebastián Ramírez · committed by GitHub · parent 0489857 · Browse files · 9 files+191 added−5 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+191 added−5 removed

  • tests:+107 added−0 removed
  • other:+84 added−5 removed

9 files+191 added−5 removed

modified:docs/tutorial/index.md+2 added-2 removed
modified:docs/index.md+1 added
269 unmodified lines
270Typer uses <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a> internally. That's the only dependency.271272But you can also install extras:273274* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank">Rich</a>: and Typer will show nicely formatted errors automatically.275* <a href="https://pypi.org/project/colorama/" class="external-link" target="_blank"><code>colorama</code></a>: and Click will automatically use it to make sure your terminal's colors always work correctly, even in Windows.276 * Then you can use any tool you want to output your terminal's colors in all the systems, including the integrated `typer.style()` and `typer.secho()` (provided by Click).277 * Or any other tool, e.g. <a href="https://pypi.org/project/wasabi/" class="external-link" target="_blank"><code>wasabi</code></a>, <a href="https://github.com/erikrose/blessings" class="external-link" target="_blank"><code>blessings</code></a>.278* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: and Typer will automatically detect the current shell when installing completion.
20 unmodified lines
added:tests/assets/type_error_no_rich.py+12 added
1import typer2import typer.main34typer.main.rich = None567def main(name: str = "morty"):8 print(name + 3)91011if __name__ == "__main__":12 typer.run(main)
added:tests/assets/type_error_normal_traceback.py+22 added
1import typer23app = typer.Typer()456@app.command()7def main(name: str = "morty"):8 print(name)91011broken_app = typer.Typer()121314@broken_app.command()15def broken(name: str = "morty"):16 print(name + 3)171819if __name__ == "__main__":20 app(standalone_mode=False)2122 typer.main.get_command(broken_app)()
added:tests/assets/type_error_rich.py+9 added
1import typer234def main(name: str = "morty"):5 print(name + 3)678if __name__ == "__main__":9 typer.run(main)
added:tests/test_tracebacks.py+64 added
1import subprocess2from pathlib import Path345def test_traceback_rich():6 file_path = Path(__file__).parent / "assets/type_error_rich.py"7 result = subprocess.run(8 ["coverage", "run", str(file_path)],9 stdout=subprocess.PIPE,10 stderr=subprocess.PIPE,11 encoding="utf-8",12 )13 assert "return get_command(self)(*args, **kwargs)" not in result.stderr1415 assert "typer.run(main)" in result.stderr16 assert "print(name + 3)" in result.stderr1718 # TODO: when deprecating Python 3.6, remove second option19 assert (20 'TypeError: can only concatenate str (not "int") to str' in result.stderr21 or "TypeError: must be str, not int" in result.stderr22 )23 assert "name = 'morty'" in result.stderr242526def test_traceback_no_rich():27 file_path = Path(__file__).parent / "assets/type_error_no_rich.py"28 result = subprocess.run(29 ["coverage", "run", str(file_path)],30 stdout=subprocess.PIPE,31 stderr=subprocess.PIPE,32 encoding="utf-8",33 )34 assert "return get_command(self)(*args, **kwargs)" not in result.stderr3536 assert "typer.run(main)" in result.stderr37 assert "print(name + 3)" in result.stderr38 # TODO: when deprecating Python 3.6, remove second option39 assert (40 'TypeError: can only concatenate str (not "int") to str' in result.stderr41 or "TypeError: must be str, not int" in result.stderr42 )434445def test_unmodified_traceback():46 file_path = Path(__file__).parent / "assets/type_error_normal_traceback.py"47 result = subprocess.run(48 ["coverage", "run", str(file_path)],49 stdout=subprocess.PIPE,50 stderr=subprocess.PIPE,51 encoding="utf-8",52 )53 assert "morty" in result.stdout, "the call to the first app should work normally"54 assert "return callback(**use_params)" in result.stderr, (55 "calling outside of Typer should show the normal traceback, "56 "even after the hook is installed"57 )58 assert "typer.main.get_command(broken_app)()" in result.stderr59 assert "print(name + 3)" in result.stderr60 # TODO: when deprecating Python 3.6, remove second option61 assert (62 'TypeError: can only concatenate str (not "int") to str' in result.stderr63 or "TypeError: must be str, not int" in result.stderr64 )
modified:typer/main.py+76 added-1 removed
1import inspect2import os3import sys4import traceback5from datetime import datetime6from enum import Enum7from functools import update_wrapper8from pathlib import Path9from traceback import FrameSummary, StackSummary10from types import TracebackType11from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type, Union12from uuid import UUID1314import click
19 unmodified lines
34 TyperInfo,35)36from .utils import get_params_from_function3738try:39 import rich40 from rich.console import Console41 from rich.traceback import Traceback4243 console_stderr = Console(stderr=True)4445except ImportError: # pragma: nocover46 rich = None # type: ignore4748_original_except_hook = sys.excepthook49_typer_developer_exception_attr_name = "__typer_developer_exception__"505152def except_hook(53 exc_type: Type[BaseException], exc_value: BaseException, tb: TracebackType54) -> None:55 if not getattr(exc_value, _typer_developer_exception_attr_name, None):56 _original_except_hook(exc_type, exc_value, tb)57 return58 typer_path = os.path.dirname(__file__)59 click_path = os.path.dirname(click.__file__)60 supress_internal_dir_names = [typer_path, click_path]61 exc = exc_value62 if rich:63 rich_tb = Traceback.from_exception(64 type(exc),65 exc,66 exc.__traceback__,67 show_locals=True,68 suppress=supress_internal_dir_names,69 )70 console_stderr.print(rich_tb)71 return72 tb_exc = traceback.TracebackException.from_exception(exc)73 stack: List[FrameSummary] = []74 for frame in tb_exc.stack:75 if any(76 [frame.filename.startswith(path) for path in supress_internal_dir_names]77 ):78 # Hide the line for internal libraries, Typer and Click79 stack.append(80 traceback.FrameSummary(81 filename=frame.filename,82 lineno=frame.lineno,83 name=frame.name,84 line="",85 )86 )87 else:88 stack.append(frame)89 # Type ignore ref: https://github.com/python/typeshed/pull/824490 final_stack_summary = StackSummary.from_list(stack) # type: ignore91 tb_exc.stack = final_stack_summary92 for line in tb_exc.format():93 print(line, file=sys.stderr)94 return959697def get_install_completion_arguments() -> Tuple[click.Parameter, click.Parameter]:98 install_param, show_param = get_completion_inspect_parameters()99 click_install_param, _ = get_click_param(install_param)100 click_show_param, _ = get_click_param(show_param)
172 unmodified lines
273 )274 )275276 def __call__(self, *args: Any, **kwargs: Any) -> Any:277 if sys.excepthook != except_hook:278 sys.excepthook = except_hook279 try:214 return get_command(self)(*args, **kwargs)280 return get_command(self)(*args, **kwargs)281 except Exception as e:282 # Set a custom attribute to tell the hook to show nice exceptions for user283 # code. An alternative/first implementation was a custom exception with284 # raise custom_exc from e285 # but that means the last error shown is the custom exception, not the286 # actual error. This trick improves developer experience by showing the287 # actual error last.288 setattr(e, _typer_developer_exception_attr_name, True)289 raise e290291292def get_group(typer_instance: Typer) -> click.Command:293 group = get_group_from_info(TyperInfo(typer_instance))
677 unmodified lines
modified:pyproject.toml+4 added-2 removed
modified:README.md+1 added
269 unmodified lines
270Typer uses <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a> internally. That's the only dependency.271272But you can also install extras:273274* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank">Rich</a>: and Typer will show nicely formatted errors automatically.275* <a href="https://pypi.org/project/colorama/" class="external-link" target="_blank"><code>colorama</code></a>: and Click will automatically use it to make sure your terminal's colors always work correctly, even in Windows.276 * Then you can use any tool you want to output your terminal's colors in all the systems, including the integrated `typer.style()` and `typer.secho()` (provided by Click).277 * Or any other tool, e.g. <a href="https://pypi.org/project/wasabi/" class="external-link" target="_blank"><code>wasabi</code></a>, <a href="https://github.com/erikrose/blessings" class="external-link" target="_blank"><code>blessings</code></a>.278* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: and Typer will automatically detect the current shell when installing completion.
20 unmodified lines