Skip to content
Myr

: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

13 files+187 added−22 removed

added:docs/src/first_steps/tutorial006.py+17 added
1import typer234def main(name: str, lastname: str = "", formal: bool = False):5 """6 Say hi to NAME, optionally with a --lastname.78 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}")141516if __name__ == "__main__":17 typer.run(main)
modified:docs/tutorial/first-steps.md+42 added-2 removed
20 unmodified lines
2122// Now check the --help23$ python main.py --help2425Usage: main.py [OPTIONS]25Usage: tryit.py [OPTIONS]2627Options: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```3233</div>34
268 unmodified lines
303```304305</div>306307## Document your CLI app308309If 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:310311```Python hl_lines="5 6 7 8 9"312{!./src/first_steps/tutorial006.py!}313```314315Now see it with the `--help` option:316317<div class="termy">318319```console320$ python main.py --help321322Usage: tutorial006.py [OPTIONS] NAME323324 Say hi to NAME, optionally with a --lastname.325326 If --formal is used, say hi very formally.327328Options: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```335336</div>337338!!! tip339 You should document the *CLI arguments* in the docstring.340341 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.342343 But *CLI arguments* are normally used for the most necessary things, so you should document them here in the *docstring*.344345## Arguments, options, parameters, optional, required346347Be 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 lines
modified:tests/test_tutorial/test_first_steps/test_tutorial001.py+1 added-1 removed
15 unmodified lines
161718def 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 line
modified:tests/test_tutorial/test_first_steps/test_tutorial002.py+1 added-1 removed
23 unmodified lines
242526def 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 line
modified:tests/test_tutorial/test_first_steps/test_tutorial003.py+1 added-1 removed
23 unmodified lines
242526def 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 line
modified:tests/test_tutorial/test_first_steps/test_tutorial004.py+1 added-1 removed
35 unmodified lines
363738def 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 line
modified:tests/test_tutorial/test_first_steps/test_tutorial005.py+1 added-1 removed
42 unmodified lines
434445def 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 line
added:tests/test_tutorial/test_first_steps/test_tutorial006.py+52 added
1import subprocess23import typer4from typer.testing import CliRunner56from first_steps import tutorial006 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def 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.output192021def test_1():22 result = runner.invoke(app, ["Camila"])23 assert result.exit_code == 024 assert "Hello Camila" in result.output252627def 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.output313233def 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.output373839def 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.output434445def 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.stdout
modified:typer/completion.py+3 added-2 removed
1import sys2from typing import Any34import click5import click_completion
8 unmodified lines
14 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)192021def 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)262728# Create a fake command function to extract the completion parameters29def _install_completion_placeholder_function(
18 unmodified lines
modified:typer/main.py+57 added-13 removed
257 unmodified lines
258 return get_command_name(typer_info.typer_instance.info.callback.__name__)259 return None260261262def 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.value294295296def 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 lines
397398def 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 lines
418 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 lines
added:.coveragerc+8 added
1[run]23source =4 typer5 tests6 docs/src78parallel = True
modified:.gitignore+2 added
5 unmodified lines
6dist7.mypy_cache8.idea9site10.coverage11htmlcov
modified:pyproject.toml+1 added
37 unmodified lines
38[tool.flit.metadata.requires-extra]39test = [40 "pytest >=4.0.0",41 "pytest-cov",42 "coverage",43 "mypy",44 "black",45 "isort"46]
9 unmodified lines