✨ Allow configuring pretty errors when creating the Typer instance (#416)
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 8500607 · Browse files · 6 files·+166 added−18 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+166 added−18 removed
- tests:+100 added−1 removed
- other:+66 added−17 removed
Provenance
- Commit
95a5233- Tree
b8a27d0- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
8500607
6 files changed+166 added−18 removed
added:tests/assets/type_error_no_rich_short_disable.py+16 added
1+import typer2+import typer.main3+4+typer.main.rich = None5+6+7+app = typer.Typer(pretty_errors_short=False)8+9+10+@app.command()11+def main(name: str = "morty"):12+ print(name + 3)13+14+15+if __name__ == "__main__":16+ app()added:tests/assets/type_error_rich_pretty_disable.py+12 added
1+import typer2+3+app = typer.Typer(pretty_errors_enable=False)4+5+6+@app.command()7+def main(name: str = "morty"):8+ print(name + 3)9+10+11+if __name__ == "__main__":12+ app()added:tests/assets/type_error_rich_short_disable.py+12 added
1+import typer2+3+app = typer.Typer(pretty_errors_short=False)4+5+6+@app.command()7+def main(name: str = "morty"):8+ print(name + 3)9+10+11+if __name__ == "__main__":12+ app()modified:tests/test_tracebacks.py+60 added-1 removed
10 unmodified lines11 encoding="utf-8",12 )13 assert "return get_command(self)(*args, **kwargs)" not in result.stderr14 15- assert "typer.run(main)" in result.stderr15+ assert "typer.run(main)" not in result.stderr16 assert "print(name + 3)" in result.stderr17 18 # TODO: when deprecating Python 3.6, remove second option19 assert (2 unmodified lines22 )23 assert "name = 'morty'" in result.stderr24 25 26+def test_traceback_rich_pretty_short_disable():27+ file_path = Path(__file__).parent / "assets/type_error_rich_short_disable.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 "app()" in result.stderr37+ assert "print(name + 3)" in result.stderr38+39+ # TODO: when deprecating Python 3.6, remove second option40+ assert (41+ 'TypeError: can only concatenate str (not "int") to str' in result.stderr42+ or "TypeError: must be str, not int" in result.stderr43+ )44+ assert "name = 'morty'" in result.stderr45+46+47 def test_traceback_no_rich():48 file_path = Path(__file__).parent / "assets/type_error_no_rich.py"49 result = subprocess.run(50 ["coverage", "run", str(file_path)],11 unmodified lines62 or "TypeError: must be str, not int" in result.stderr63 )64 65 66+def test_traceback_no_rich_short_disable():67+ file_path = Path(__file__).parent / "assets/type_error_no_rich_short_disable.py"68+ result = subprocess.run(69+ ["coverage", "run", str(file_path)],70+ stdout=subprocess.PIPE,71+ stderr=subprocess.PIPE,72+ encoding="utf-8",73+ )74+ assert "return get_command(self)(*args, **kwargs)" not in result.stderr75+76+ assert "app()" in result.stderr77+ assert "print(name + 3)" in result.stderr78+ # TODO: when deprecating Python 3.6, remove second option79+ assert (80+ 'TypeError: can only concatenate str (not "int") to str' in result.stderr81+ or "TypeError: must be str, not int" in result.stderr82+ )83+84+85 def test_unmodified_traceback():86 file_path = Path(__file__).parent / "assets/type_error_normal_traceback.py"87 result = subprocess.run(88 ["coverage", "run", str(file_path)],12 unmodified lines101 assert (102 'TypeError: can only concatenate str (not "int") to str' in result.stderr103 or "TypeError: must be str, not int" in result.stderr104 )105+106+107+def test_rich_pretty_errors_disable():108+ file_path = Path(__file__).parent / "assets/type_error_rich_pretty_disable.py"109+ result = subprocess.run(110+ ["coverage", "run", str(file_path)],111+ stdout=subprocess.PIPE,112+ stderr=subprocess.PIPE,113+ encoding="utf-8",114+ )115+ assert "return get_command(self)(*args, **kwargs)" in result.stderr116+117+ assert "app()" in result.stderr118+ assert "print(name + 3)" in result.stderr119+ # TODO: when deprecating Python 3.6, remove second option120+ assert (121+ 'TypeError: can only concatenate str (not "int") to str' in result.stderr122+ or "TypeError: must be str, not int" in result.stderr123+ )modified:typer/main.py+53 added-17 removed
20 unmodified lines21 CommandFunctionType,22 CommandInfo,23 Default,24 DefaultPlaceholder,25+ DeveloperExceptionConfig,26 FileBinaryRead,27 FileBinaryWrite,28 FileText,29 FileTextWrite,22 unmodified lines52 53 def except_hook(54 exc_type: Type[BaseException], exc_value: BaseException, tb: TracebackType55 ) -> None:55- if not getattr(exc_value, _typer_developer_exception_attr_name, None):56+ exception_config: Union[DeveloperExceptionConfig, None] = getattr(57+ exc_value, _typer_developer_exception_attr_name, None58+ )59+ if not exception_config or not exception_config.pretty_errors_enable:60 _original_except_hook(exc_type, exc_value, tb)61 return62 typer_path = os.path.dirname(__file__)63 click_path = os.path.dirname(click.__file__)3 unmodified lines67 rich_tb = Traceback.from_exception(68 type(exc),69 exc,70 exc.__traceback__,67- show_locals=True,71+ show_locals=exception_config.pretty_errors_show_locals,72 suppress=supress_internal_dir_names,73 )74 console_stderr.print(rich_tb)75 return2 unmodified lines78 for frame in tb_exc.stack:79 if any(80 [frame.filename.startswith(path) for path in supress_internal_dir_names]81 ):82+ if not exception_config.pretty_errors_short: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="",83+ # Hide the line for internal libraries, Typer and Click84+ stack.append(85+ traceback.FrameSummary(86+ filename=frame.filename,87+ lineno=frame.lineno,88+ name=frame.name,89+ line="",90+ )91 )86- )92 else:93 stack.append(frame)94 # Type ignore ref: https://github.com/python/typeshed/pull/824495 final_stack_summary = StackSummary.from_list(stack) # type: ignore31 unmodified lines127 add_help_option: bool = Default(True),128 hidden: bool = Default(False),129 deprecated: bool = Default(False),130 add_completion: bool = True,131+ pretty_errors_enable: bool = True,132+ pretty_errors_show_locals: bool = True,133+ pretty_errors_short: bool = True,134 ):135 self._add_completion = add_completion136+ self.pretty_errors_enable = pretty_errors_enable137+ self.pretty_errors_show_locals = pretty_errors_show_locals138+ self.pretty_errors_short = pretty_errors_short139 self.info = TyperInfo(140 name=name,141 cls=cls,142 invoke_without_command=invoke_without_command,152 unmodified lines295 # raise custom_exc from e296 # but that means the last error shown is the custom exception, not the297 # actual error. This trick improves developer experience by showing the298 # actual error last.288- setattr(e, _typer_developer_exception_attr_name, True)299+ setattr(300+ e,301+ _typer_developer_exception_attr_name,302+ DeveloperExceptionConfig(303+ pretty_errors_enable=self.pretty_errors_enable,304+ pretty_errors_show_locals=self.pretty_errors_show_locals,305+ pretty_errors_short=self.pretty_errors_short,306+ ),307+ )308 raise e309 310 311 def get_group(typer_instance: Typer) -> click.Command:293- group = get_group_from_info(TyperInfo(typer_instance))312+ group = get_group_from_info(313+ TyperInfo(typer_instance),314+ pretty_errors_short=typer_instance.pretty_errors_short,315+ )316 return group317 318 319 def get_command(typer_instance: Typer) -> click.Command:19 unmodified lines339 typer_instance.info.context_settings, DefaultPlaceholder340 ):341 single_command.context_settings = typer_instance.info.context_settings342 321- click_command = get_command_from_info(single_command)343+ click_command = get_command_from_info(344+ single_command, pretty_errors_short=typer_instance.pretty_errors_short345+ )346 if typer_instance._add_completion:347 click_command.params.append(click_install_param)348 click_command.params.append(click_show_param)349 return click_command95 unmodified lines445 values["help"] = solve_typer_info_help(typer_info)446 return TyperInfo(**values)447 448 425-def get_group_from_info(group_info: TyperInfo) -> click.Command:449+def get_group_from_info(450+ group_info: TyperInfo, *, pretty_errors_short: bool451+) -> click.Command:452 assert (453 group_info.typer_instance454 ), "A Typer instance is needed to generate a Click Group"455 commands: Dict[str, click.Command] = {}456 for command_info in group_info.typer_instance.registered_commands:431- command = get_command_from_info(command_info=command_info)457+ command = get_command_from_info(458+ command_info=command_info, pretty_errors_short=pretty_errors_short459+ )460 if command.name:461 commands[command.name] = command462 for sub_group_info in group_info.typer_instance.registered_groups:435- sub_group = get_group_from_info(sub_group_info)463+ sub_group = get_group_from_info(464+ sub_group_info, pretty_errors_short=pretty_errors_short465+ )466 if sub_group.name:467 commands[sub_group.name] = sub_group468 solved_info = solve_typer_info_defaults(group_info)469 (15 unmodified lines485 callback=solved_info.callback,486 params=params,487 convertors=convertors,488 context_param_name=context_param_name,489+ pretty_errors_short=pretty_errors_short,490 ),491 params=params, # type: ignore492 help=solved_info.help,493 epilog=solved_info.epilog,28 unmodified lines522 params.append(click_param)523 return params, convertors, context_param_name524 525 495-def get_command_from_info(command_info: CommandInfo) -> click.Command:526+def get_command_from_info(527+ command_info: CommandInfo, *, pretty_errors_short: bool528+) -> click.Command:529 assert command_info.callback, "A command must have a callback function"530 name = command_info.name or get_command_name(command_info.callback.__name__)531 use_help = command_info.help532 if use_help is None:13 unmodified lines546 callback=command_info.callback,547 params=params,548 convertors=convertors,549 context_param_name=context_param_name,550+ pretty_errors_short=pretty_errors_short,551 ),552 params=params, # type: ignore553 help=use_help,554 epilog=command_info.epilog,63 unmodified lines618 callback: Optional[Callable[..., Any]] = None,619 params: Sequence[click.Parameter] = [],620 convertors: Dict[str, Callable[[str], Any]] = {},621 context_param_name: Optional[str] = None,622+ pretty_errors_short: bool,623 ) -> Optional[Callable[..., Any]]:624 if not callback:625 return None626 parameters = get_params_from_function(callback)4 unmodified lines631 if param.name:632 use_params[param.name] = param.default633 634 def wrapper(**kwargs: Any) -> Any:635+ _rich_traceback_guard = pretty_errors_short # noqa: F841636 for k, v in kwargs.items():637 if k in convertors:638 use_params[k] = convertors[k](v)639 else:367 unmodified linesmodified:typer/models.py+13 added
452 unmodified lines453 ) -> None:454 self.name = name455 self.default = default456 self.annotation = annotation457+458+459+class DeveloperExceptionConfig:460+ def __init__(461+ self,462+ *,463+ pretty_errors_enable: bool = True,464+ pretty_errors_show_locals: bool = True,465+ pretty_errors_short: bool = True,466+ ) -> None:467+ self.pretty_errors_enable = pretty_errors_enable468+ self.pretty_errors_show_locals = pretty_errors_show_locals469+ self.pretty_errors_short = pretty_errors_short