:bug: Fix and document extracting help form docstring
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 · parents a650881, f00e100 · Browse files · 13 files·+187 added−22 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+187 added−22 removed
- tests:+57 added−5 removed
- other:+130 added−17 removed
Provenance
- Commit
a8bc1b7- Tree
06881cf- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
a650881- Parent 2
f00e100
13 files changed+187 added−22 removed
added:docs/src/first_steps/tutorial006.py+17 added
1+import typer2+3+4+def main(name: str, lastname: str = "", formal: bool = False):5+ """6+ Say hi to NAME, optionally with a --lastname.7+8+ If --formal is used, say hi very formally.9+ """10+ if formal:11+ typer.echo(f"Good day Ms. {name} {lastname}.")12+ else:13+ typer.echo(f"Hello {name} {lastname}")14+15+16+if __name__ == "__main__":17+ typer.run(main)modified:docs/tutorial/first-steps.md+42 added-2 removed
20 unmodified lines21 22 // Now check the --help23 $ python main.py --help24 25-Usage: main.py [OPTIONS]25+Usage: tryit.py [OPTIONS]26 27 Options:28+ --install-completion Install completion for the current shell.29+ --show-completion Show completion for the current shell, to copy it or customize the installation.28- --help Show this message and exit.30+ --help Show this message and exit.31 ```32 33 </div>34 268 unmodified lines303 ```304 305 </div>306 307+## Document your CLI app308+309+If you add a <abbr title="a multi-line string as the first expression inside a function (not assigned to any variable) used for documentation">docstring</abbr> to your function it will be used in the help text:310+311+```Python hl_lines="5 6 7 8 9"312+{!./src/first_steps/tutorial006.py!}313+```314+315+Now see it with the `--help` option:316+317+<div class="termy">318+319+```console320+$ python main.py --help321+322+Usage: tutorial006.py [OPTIONS] NAME323+324+ Say hi to NAME, optionally with a --lastname.325+326+ If --formal is used, say hi very formally.327+328+Options:329+ --lastname TEXT330+ --formal / --no-formal331+ --install-completion Install completion for the current shell.332+ --show-completion Show completion for the current shell, to copy it or customize the installation.333+ --help Show this message and exit.334+```335+336+</div>337+338+!!! tip339+ You should document the *CLI arguments* in the docstring.340+341+ There is another place to document the *CLI options* that will show up next to them in the help text as with `--install-completion` or `--help`, you will learn that later in the tutorial.342+343+ But *CLI arguments* are normally used for the most necessary things, so you should document them here in the *docstring*.344+345 ## Arguments, options, parameters, optional, required346 347 Be aware that these terms refer to multiple things depending on the context, and sadly, those "contexts" mix frequently, so it's easy to get confused.348 65 unmodified linesmodified:tests/test_tutorial/test_first_steps/test_tutorial001.py+1 added-1 removed
15 unmodified lines16 17 18 def test_script():19 result = subprocess.run(20- ["coverage", "run", "--parallel-mode", mod.__file__, "--help"],20+ ["coverage", "run", mod.__file__, "--help"],21 stdout=subprocess.PIPE,22 stderr=subprocess.PIPE,23 encoding="utf-8",24 )1 unmodified linemodified:tests/test_tutorial/test_first_steps/test_tutorial002.py+1 added-1 removed
23 unmodified lines24 25 26 def test_script():27 result = subprocess.run(28- ["coverage", "run", "--parallel-mode", mod.__file__, "--help"],28+ ["coverage", "run", mod.__file__, "--help"],29 stdout=subprocess.PIPE,30 stderr=subprocess.PIPE,31 encoding="utf-8",32 )1 unmodified linemodified:tests/test_tutorial/test_first_steps/test_tutorial003.py+1 added-1 removed
23 unmodified lines24 25 26 def test_script():27 result = subprocess.run(28- ["coverage", "run", "--parallel-mode", mod.__file__, "--help"],28+ ["coverage", "run", mod.__file__, "--help"],29 stdout=subprocess.PIPE,30 stderr=subprocess.PIPE,31 encoding="utf-8",32 )1 unmodified linemodified:tests/test_tutorial/test_first_steps/test_tutorial004.py+1 added-1 removed
35 unmodified lines36 37 38 def test_script():39 result = subprocess.run(40- ["coverage", "run", "--parallel-mode", mod.__file__, "--help"],40+ ["coverage", "run", mod.__file__, "--help"],41 stdout=subprocess.PIPE,42 stderr=subprocess.PIPE,43 encoding="utf-8",44 )1 unmodified linemodified:tests/test_tutorial/test_first_steps/test_tutorial005.py+1 added-1 removed
42 unmodified lines43 44 45 def test_script():46 result = subprocess.run(47- ["coverage", "run", "--parallel-mode", mod.__file__, "--help"],47+ ["coverage", "run", mod.__file__, "--help"],48 stdout=subprocess.PIPE,49 stderr=subprocess.PIPE,50 encoding="utf-8",51 )1 unmodified lineadded:tests/test_tutorial/test_first_steps/test_tutorial006.py+52 added
1+import subprocess2+3+import typer4+from typer.testing import CliRunner5+6+from first_steps import tutorial006 as mod7+8+runner = CliRunner()9+10+app = typer.Typer()11+app.command()(mod.main)12+13+14+def test_help():15+ result = runner.invoke(app, ["--help"])16+ assert result.exit_code == 017+ assert "Say hi to NAME, optionally with a --lastname." in result.output18+ assert "If --formal is used, say hi very formally." in result.output19+20+21+def test_1():22+ result = runner.invoke(app, ["Camila"])23+ assert result.exit_code == 024+ assert "Hello Camila" in result.output25+26+27+def test_option_lastname():28+ result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])29+ assert result.exit_code == 030+ assert "Hello Camila Gutiérrez" in result.output31+32+33+def test_option_lastname_2():34+ result = runner.invoke(app, ["--lastname", "Gutiérrez", "Camila"])35+ assert result.exit_code == 036+ assert "Hello Camila Gutiérrez" in result.output37+38+39+def test_formal_1():40+ result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez", "--formal"])41+ assert result.exit_code == 042+ assert "Good day Ms. Camila Gutiérrez." in result.output43+44+45+def test_script():46+ result = subprocess.run(47+ ["coverage", "run", mod.__file__, "--help"],48+ stdout=subprocess.PIPE,49+ stderr=subprocess.PIPE,50+ encoding="utf-8",51+ )52+ assert "Usage" in result.stdoutmodified:typer/completion.py+3 added-2 removed
1+import sys2 from typing import Any3 4 import click5 import click_completion8 unmodified lines14 if not value or ctx.resilient_parsing:15 return value16 shell, path = click_completion.core.install()17 click.echo(f"{shell} completion installed in {path}")17- exit(0)18+ sys.exit(0)19 20 21 def show_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:22 if not value or ctx.resilient_parsing:23 return value24 click.echo(click_completion.core.get_code())24- exit(0)25+ sys.exit(0)26 27 28 # Create a fake command function to extract the completion parameters29 def _install_completion_placeholder_function(18 unmodified linesmodified:typer/main.py+57 added-13 removed
257 unmodified lines258 return get_command_name(typer_info.typer_instance.info.callback.__name__)259 return None260 261 262+def solve_typer_info_help(typer_info: TyperInfo) -> str:263+ # Priority 1a: Value was set in app.add_typer()264+ if not isinstance(typer_info.help, DefaultPlaceholder):265+ return inspect.cleandoc(typer_info.help or "")266+ # Priority 1b: Value was set in app.add_typer(), in callback docstring267+ if typer_info.callback:268+ doc = inspect.getdoc(typer_info.callback)269+ if doc:270+ return doc271+ try:272+ # Priority 2a: Value was set in @subapp.callback()273+ doc = typer_info.typer_instance.registered_callback.help274+ if not isinstance(doc, DefaultPlaceholder):275+ return inspect.cleandoc(doc or "")276+ # Priority 2b: Value was set in @subapp.callback(), in callback docstring277+ doc = inspect.getdoc(typer_info.typer_instance.registered_callback.callback)278+ if doc:279+ return doc280+ except AttributeError:281+ pass282+ try:283+ # Priority 3a: Value set in subapp = typer.Typer()284+ instance_value = typer_info.typer_instance.info.help285+ if not isinstance(instance_value, DefaultPlaceholder):286+ return inspect.cleandoc(instance_value or "")287+ doc = inspect.getdoc(typer_info.typer_instance.callback)288+ if doc:289+ return doc290+ except AttributeError:291+ pass292+ # Value not set, use the default293+ return typer_info.help.value294+295+296 def solve_typer_info_defaults(typer_info: TyperInfo) -> TyperInfo:263- values = {}297+ values: Dict[str, Any] = {}298+ values["help"] = solve_typer_info_help(typer_info)299 name = None300 for name, value in typer_info.__dict__.items():301 # Priority 1: Value was set in app.add_typer()302 if not isinstance(value, DefaultPlaceholder):303 values[name] = value304 continue270- if typer_info.typer_instance:271- if typer_info.typer_instance.registered_callback:272- callback_value = getattr(273- typer_info.typer_instance.registered_callback, name274- )275- # Priority 2: Value was set in @subapp.callback()276- if not isinstance(callback_value, DefaultPlaceholder):277- values[name] = callback_value278- continue279- instance_value = getattr(typer_info.typer_instance.info, name)280- # Priority 3: Value set in subapp = typer.Typer()305+ # Priority 2: Value was set in @subapp.callback()306+ try:307+ callback_value = getattr(308+ typer_info.typer_instance.registered_callback, name # type: ignore309+ )310+ if not isinstance(callback_value, DefaultPlaceholder):311+ values[name] = callback_value312+ continue313+ except AttributeError:314+ pass315+ # Priority 3: Value set in subapp = typer.Typer()316+ try:317+ instance_value = getattr(typer_info.typer_instance.info, name) # type: ignore318 if not isinstance(instance_value, DefaultPlaceholder):319 values[name] = instance_value320 continue321+ except AttributeError:322+ pass323 # Value not set, use the default324 values[name] = value.value325 if values["name"] is None:326 values["name"] = get_group_name(typer_info)70 unmodified lines397 398 def get_command_from_info(command_info: CommandInfo) -> click.Command:399 assert command_info.callback, "A command must have a callback function"400 name = command_info.name or get_command_name(command_info.callback.__name__)401+ use_help = command_info.help402+ if use_help is None:403+ use_help = inspect.getdoc(command_info.callback)404+ else:405+ use_help = inspect.cleandoc(use_help)406 (407 params,408 convertors,409 context_param_name,8 unmodified lines418 convertors=convertors,419 context_param_name=context_param_name,420 ),421 params=params, # type: ignore378- help=command_info.help,422+ help=use_help,423 epilog=command_info.epilog,424 short_help=command_info.short_help,425 options_metavar=command_info.options_metavar,426 add_help_option=command_info.add_help_option,288 unmodified linesadded:.coveragerc+8 added
1+[run]2+3+source =4+ typer5+ tests6+ docs/src7+8+parallel = Truemodified:.gitignore+2 added
5 unmodified lines6 dist7 .mypy_cache8 .idea9 site10+.coverage11+htmlcovmodified:pyproject.toml+1 added
37 unmodified lines38 [tool.flit.metadata.requires-extra]39 test = [40 "pytest >=4.0.0",41 "pytest-cov",42+ "coverage",43 "mypy",44 "black",45 "isort"46 ]9 unmodified lines