✨ 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
Provenance
- Commit
252ed30- Tree
9abde63- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
0489857
9 files changed+191 added−5 removed
modified:docs/tutorial/index.md+2 added-2 removed
68 unmodified lines69707172737374757677787868 unmodified lines
```console$ pip install typer[all]---> 100%Successfully installed typer click colorama shellinghamSuccessfully installed typer click colorama shellingham rich```
</div>
...that also includes `colorama` and `shellingham`....that also includes `colorama`, `shellingham`, and `rich`.modified:docs/index.md+1 added
269 unmodified lines270 Typer uses <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a> internally. That's the only dependency.271 272 But you can also install extras:273 274+* <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 linesadded:tests/assets/type_error_no_rich.py+12 added
1+import typer2+import typer.main3+4+typer.main.rich = None5+6+7+def main(name: str = "morty"):8+ print(name + 3)9+10+11+if __name__ == "__main__":12+ typer.run(main)added:tests/assets/type_error_normal_traceback.py+22 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def main(name: str = "morty"):8+ print(name)9+10+11+broken_app = typer.Typer()12+13+14+@broken_app.command()15+def broken(name: str = "morty"):16+ print(name + 3)17+18+19+if __name__ == "__main__":20+ app(standalone_mode=False)21+22+ typer.main.get_command(broken_app)()added:tests/assets/type_error_rich.py+9 added
1+import typer2+3+4+def main(name: str = "morty"):5+ print(name + 3)6+7+8+if __name__ == "__main__":9+ typer.run(main)added:tests/test_tracebacks.py+64 added
1+import subprocess2+from pathlib import Path3+4+5+def 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.stderr14+15+ assert "typer.run(main)" in result.stderr16+ assert "print(name + 3)" in result.stderr17+18+ # 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.stderr24+25+26+def 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.stderr35+36+ 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+ )43+44+45+def 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
1 import inspect2+import os3+import sys4+import traceback5 from datetime import datetime6 from enum import Enum7 from functools import update_wrapper8 from pathlib import Path9+from traceback import FrameSummary, StackSummary10+from types import TracebackType11 from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type, Union12 from uuid import UUID13 14 import click19 unmodified lines34 TyperInfo,35 )36 from .utils import get_params_from_function37 38+try:39+ import rich40+ from rich.console import Console41+ from rich.traceback import Traceback42 43+ console_stderr = Console(stderr=True)44+45+except ImportError: # pragma: nocover46+ rich = None # type: ignore47+48+_original_except_hook = sys.excepthook49+_typer_developer_exception_attr_name = "__typer_developer_exception__"50+51+52+def 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+ return95+96+97 def 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 lines273 )274 )275 276 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 e290 291 292 def get_group(typer_instance: Typer) -> click.Command:293 group = get_group_from_info(TyperInfo(typer_instance))677 unmodified linesmodified:pyproject.toml+4 added-2 removed
43 unmodified lines44454647484849505152535 unmodified lines59606162626364656667686 unmodified lines43 unmodified lines "pytest-xdist >=1.32.0,<2.0.0", "pytest-sugar >=0.9.4,<0.10.0", "mypy ==0.910", "black >=22.3.0,<23.0.0", "isort >=5.0.6,<6.0.0" "isort >=5.0.6,<6.0.0", "rich >=10.11.0,<13.0.0",]doc = [ "mkdocs >=1.1.2,<2.0.0", "mkdocs-material >=8.1.4,<9.0.0",5 unmodified lines "pre-commit >=2.17.0,<3.0.0",]all = [ "colorama >=0.4.3,<0.5.0", "shellingham >=1.3.0,<2.0.0" "shellingham >=1.3.0,<2.0.0", "rich >=10.11.0,<13.0.0",]
[tool.isort]profile = "black"6 unmodified linesmodified:README.md+1 added
269 unmodified lines270 Typer uses <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a> internally. That's the only dependency.271 272 But you can also install extras:273 274+* <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