Skip to content
Myr

:sparkles: Add docs for CLI Options with tests

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

Add docs for CLI Options with tests

authored by Sebastián Ramírez · committed by GitHub · parents 5aa9bdd, 175bb67 · Browse files · 25 files+640 added−23 removed
This commit

State

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

Diff stats

25 files+640 added−23 removed

  • tests:+254 added−0 removed
  • other:+386 added−23 removed

25 files+640 added−23 removed

modified:docs/css/custom.css+6 added-1 removed
modified:docs/js/custom.js+17 added-3 removed
modified:docs/js/termynal.js+2 added-4 removed
241 unmodified lines
242 if (prop === 'class') {243 attrs += ` class=${line[prop]} `244 continue245 }246 attrs += this.pfx;247246 if (prop === 'type') {249 attrs += `="${line[prop]}" `247 attrs += `${this.pfx}="${line[prop]}" `248 } else if (prop !== 'value') {251 attrs += `-${prop}="${line[prop]}" `249 attrs += `${this.pfx}-${prop}="${line[prop]}" `250 }251 }252253 return attrs;
11 unmodified lines
added:docs/src/options/tutorial001.py+21 added
1import typer234def main(5 name: str,6 lastname: str = typer.Option("", help="Last name of person to greet."),7 formal: bool = typer.Option(False, help="Say hi formally."),8):9 """10 Say hi to NAME, optionally with a --lastname.1112 If --formal is used, say hi very formally.13 """14 if formal:15 typer.echo(f"Good day Ms. {name} {lastname}.")16 else:17 typer.echo(f"Hello {name} {lastname}")181920if __name__ == "__main__":21 typer.run(main)
added:docs/src/options/tutorial002.py+9 added
1import typer234def main(name: str, lastname: str = typer.Option(...)):5 typer.echo(f"Hello {name} {lastname}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/options/tutorial003.py+9 added
1import typer234def main(name: str, lastname: str = typer.Option(..., prompt=True)):5 typer.echo(f"Hello {name} {lastname}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/options/tutorial004.py+12 added
1import typer234def main(5 name: str,6 lastname: str = typer.Option(..., prompt="Please tell me your last name"),7):8 typer.echo(f"Hello {name} {lastname}")91011if __name__ == "__main__":12 typer.run(main)
added:docs/src/options/tutorial005.py+9 added
1import typer234def main(project_name: str = typer.Option(..., prompt=True, confirmation_prompt=True)):5 typer.echo(f"Deleting project {project_name}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/options/tutorial006.py+9 added
1import typer234def main(fullname: str = typer.Option("Wade Wilson", show_default=True)):5 typer.echo(f"Hello {fullname}")678if __name__ == "__main__":9 typer.run(main)
modified:docs/tutorial/first-steps.md+21 added-9 removed
20 unmodified lines
2122// Now check the --help23$ python main.py --help2425Usage: tryit.py [OPTIONS]25Usage: main.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.
143 unmodified lines
173</div>174175The main visual difference between a *CLI option* and and a *CLI argument* is that the *CLI option* has `--` prepended to the name, like in "`--size`".176177A *CLI option* doesn't depend on the order because it has a predefined name (here it's `--size`). This is because the CLI app is looking specifically for a literal `--size` parameter or "flag", with that specific "name" (here the specific name is "`--size`"). The CLI app will check if you typed it or not, it will be actively looking for `--size` even if you didn't type it (to check if it's there or not).177A *CLI option* doesn't depend on the order because it has a predefined name (here it's `--size`). This is because the CLI app is looking specifically for a literal `--size` parameter (also known as "flag" or "switch"), with that specific "name" (here the specific name is "`--size`"). The CLI app will check if you typed it or not, it will be actively looking for `--size` even if you didn't type it (to check if it's there or not).178179In contrast, the CLI app is not actively looking for the *CLI argument* with a text "`./myproject`", it has no way to know if you would type `./myproject` or `./mysuperawesomeproject` or anything else. It's just waiting to get whatever you give it. The only way to know that you refer to a specific *CLI argument* is because of the order. The same way that it knows that the first *CLI argument* was the `name` and the second was the `lastname`, but if you mixed the order, it wouldn't be able to handle it.179In contrast, the CLI app is not actively looking for the *CLI argument* with a text "`./myproject`", it has no way to know if you would type `./myproject` or `./my-super-awesome-project` or anything else. It's just waiting to get whatever you give it. The only way to know that you refer to a specific *CLI argument* is because of the order. The same way that it knows that the first *CLI argument* was the `name` and the second was the `lastname`, but if you mixed the order, it wouldn't be able to handle it.180181Instead, with a *CLI option*, the order doesn't matter.182183Also, by default, a *CLI option* is *optional* (not *required*).184185So, by default:186187* A *CLI argument* is **required**188* A *CLI option* is **optional**189190But the *required* and *optional* defaults can be changed.191192So, the main and **most important** difference is that:193194* *CLI options* **start with `--`** and don't depend on the order195* *CLI arguments* depend on the **sequence order**196197!!! tip186 In this example above the *CLI option* `--size` is just a "flag", it's a boolean value, `True` or `False`.198 In this example above the *CLI option* `--size` is just a "flag" or "switch" that will contain a boolean value, `True` or `False`, depending on if it was added to the command or not.199200 This one doesn't receive any values. But *CLI options* can also receive values like *CLI arguments*. You'll see how later.201202## Add one *CLI option*
127 unmodified lines
330331```console332$ python main.py --help333322Usage: tutorial006.py [OPTIONS] NAME334Usage: main.py [OPTIONS] NAME335336 Say hi to NAME, optionally with a --lastname.337338 If --formal is used, say hi very formally.
66 unmodified lines
405And a parameter like `name`, that doesn't have a default value, is considered *required*.406407### In CLIs408397When talking about command line interfaces/applications, the words "argument" and "parameter" are commonly used to refer to that data passed to a CLI app, those parameters.409When talking about command line interfaces/applications, the words **"argument"** and **"parameter"** are commonly used to refer to that data passed to a CLI app, those parameters.410399But those words don't imply anything about the data being required, needing to be passed in a certain order, nor having a flag like `--lastname`.411But those words **don't imply** anything about the data being required, needing to be passed in a certain order, nor having a flag like `--lastname`.412401The parameters that come with a flag like `--lastname` and a value (or when the flag itself is the value, like `--formal`) are commonly optional, not required. So, when talking about CLIs it's common to call them *optional arguments* or *optional parameters*.413The parameters that come with a name like `--lastname` (and optionally a value) are commonly optional, not required. So, when talking about CLIs it's common to call them **optional arguments** or **optional parameters**. Sometimes these *optional parameters* that start with `--` are also called a **flag** or a **switch**.414415In reality, the parameters that require an order can be made *optional* too. And the ones that come with a flag (like `--lastname`) can be *required* too.416417### In **Typer**
1 unmodified line
419To try and make it a bit easier, we'll normally use the words "parameter" or "argument" to refer to Python functions.420421We'll use ***CLI argument*** to refer to those *CLI parameters* that depend on an order. That are **required** by default.422411And we'll use ***CLI option*** to refer to those *CLI parameters* that depend on a flag (like `--lastname`). That are **optional** by default.423And we'll use ***CLI option*** to refer to those *CLI parameters* that depend on a name that starts with `--` (like `--lastname`). That are **optional** by default.424425We will use ***CLI parameter*** to refer to both, *CLI arguments* and *CLI options*.
added:docs/tutorial/options.md+263 added
1## *CLI options* with help23In the *First Steps* section you saw how to add help for a CLI app/command by adding it to a function's <abbr title="a multi-line string as the first expression inside a function (not assigned to any variable) used for documentation">docstring</abbr>.45Here's how that last example looked like:67```Python8{!./src/first_steps/tutorial006.py!}9```1011Now we'll add a *help* section to the *CLI options*:1213```Python hl_lines="6 7"14{!./src/options/tutorial001.py!}15```1617We are replacing the default values we had before with `typer.Option()`.1819As we no longer have a default value there, the first parameter to `typer.Option()` serves the same purpose of defining that default value.2021So, if we had:2223```Python24lastname: str = ""25```2627now we write:2829```Python30lastname: str = typer.Option("")31```3233And both forms achieve the same: a *CLI option* with a default value of an empty string (`""`).3435And then we can pass the `help` keyword parameter:3637```Python38lastname: str = typer.Option("", help="this option does this and that")39```4041to create the help for that *CLI option*.4243Copy that example from above to a file `main.py`.4445Test it:4647<div class="termy">4849```console50$ python main.py --help5152Usage: main.py [OPTIONS] NAME5354 Say hi to NAME, optionally with a --lastname.5556 If --formal is used, say hi very formally.5758Options:59 --lastname TEXT Last name of person to greet.60 --formal / --no-formal Say hi formally.61 --install-completion Install completion for the current shell.62 --show-completion Show completion for the current shell, to copy it or customize the installation.63 --help Show this message and exit.6465// Now you have a help text for the --lastname and --formal CLI options 🎉66```6768</div>6970## Make a *CLI option* required7172We said before that *by default*:7374* *CLI options* are **optional**75* *CLI arguments* are **required**7677Well, that's how they work *by default*, and that's the convention in many CLI programs and systems.7879But if you really want, you can change that.8081To make a *CLI option* required, pass `...` to `typer.Option()`.8283!!! info84 If you hadn't seen that `...` before: it is a a special single value, it is <a href="https://docs.python.org/3/library/constants.html#Ellipsis" target="_blank">part of Python and is called "Ellipsis"</a>.8586That will tell **Typer** that it's still a *CLI option*, but it doesn't have a default value, and it's required.8788Let's make the `--lastname` a required *CLI option*.8990We'll also simplify the example to focus on the new parts:9192```Python hl_lines="4"93{!./src/options/tutorial002.py!}94```9596!!! tip97 You could still add `help` to `typer.Option()` as before, but we are omitting it here to simplify the example.9899And test it:100101<div class="termy">102103```console104// Pass the NAME CLI argument105$ python main.py Camila106107// We didn't pass the now required --lastname CLI option108Usage: main.py [OPTIONS] NAME109Try "main.py --help" for help.110111Error: Missing option "--lastname".112113// Now update it to pass the required --lastname CLI option114$ python main.py Camila --lastname Gutiérrez115116Hello Camila Gutiérrez117118// And if you check the help119$ python main.py --help120121Usage: main.py [OPTIONS] NAME122123Options:124 --lastname TEXT [required]125 --install-completion Install completion for the current shell.126 --show-completion Show completion for the current shell, to copy it or customize the installation.127 --help Show this message and exit.128129// It now tells you that --lastname is required 🎉130```131132</div>133134## Prompt for a *CLI option*135136It's also possible to, instead of just showing an error, ask for the missing value with `prompt=True`:137138```Python hl_lines="4"139{!./src/options/tutorial003.py!}140```141142And then your program will ask the user for it in the terminal:143144<div class="termy">145146```console147// Call it with the NAME CLI argument148$ python main.py Camila149150// It asks for the missing CLI option --lastname151# Lastname: $ Gutiérrez152153Hello Camila Gutiérrez154```155156</div>157158### Customize the prompt159160You can also set a custom prompt, passing the string that you want to use instead of just `True`:161162```Python hl_lines="6"163{!./src/options/tutorial004.py!}164```165166And then your program will ask for it using with your custom prompt:167168<div class="termy">169170```console171// Call it with the NAME CLI argument172$ python main.py Camila173174// It uses the custom prompt175# Please tell me your last name: $ Gutiérrez176177Hello Camila Gutiérrez178```179180</div>181182## Confirmation prompt183184In some cases you could want to prompt for something and then ask the user to confirm it by typing it twice.185186You can do it passing the parameter `confirmation_prompt=True`.187188Let's say it's a CLI app to delete a project:189190```Python hl_lines="4"191{!./src/options/tutorial005.py!}192```193194And it will prompt the user for a value and then for the confirmation:195196<div class="termy">197198```console199$ python main.py200201// Your app will first prompt for the project name, and then for the confirmation202# Project name: $ Old Project203# Repeat for confirmation: $ Old Project204205Deleting project Old Project206207// If the user doesn't type the same, receives an error and a new prompt208$ python main.py209210# Project name: $ Old Project211# Repeat for confirmation: $ New Spice212213Error: the two entered values do not match214215# Project name: $ Old Project216# Repeat for confirmation: $ Old Project217218Deleting project Old Project219220// Now it works 🎉221```222223</div>224225## Show default in help226227You can tell Typer to show the default value in the help text with `show_default=True`:228229```Python hl_lines="4"230{!./src/options/tutorial006.py!}231```232233And it will show up in the help text:234235<div class="termy">236237```console238$ python main.py239240Hello Wade Wilson241242// Show the help243$ python main.py --help244245Usage: main.py [OPTIONS]246247Options:248 --fullname TEXT [default: Wade Wilson]249 --install-completion Install completion for the current shell.250 --show-completion Show completion for the current shell, to copy it or customize the installation.251 --help Show this message and exit.252```253254</div>255256!!! tip257 Notice the `[default: Wade Wilson]` in the help text.258259## Other uses260261`typer.Option()` has several other users. For data validation, to enable other features, etc.262263But you will see about that later in the docs.
modified:docs/index.md+1 added-1 removed
96 unmodified lines
97 --install-completion Install completion for the current shell.98 --show-completion Show completion for the current shell, to copy it or customize the installation.99 --help Show this message and exit.100101// You get a ✨ auto completion ✨ for free, installed with --install-completion101// You get ✨ auto completion ✨ for free, installed with --install-completion102103// Now pass the NAME argument104$ python main.py Camila105
169 unmodified lines
modified:docs/release-notes.md+1 added-1 removed
1 unmodified line
23## 0.0.545* Clean exports from Typer. Remove unneeded components from Click and add needed `Exit` exception. PR [#11](https://github.com/tiangolo/typer/pull/11).6* Fix and document extracting help from a functions' docstring [First Steps: Document your CLI app](https://typer.tiangolo.com/tutorial/first-steps/#document-your-cli-app). PR [#10](https://github.com/tiangolo/typer/pull/10).6* Fix and document extracting help from a function's docstring [First Steps: Document your CLI app](https://typer.tiangolo.com/tutorial/first-steps/#document-your-cli-app). PR [#10](https://github.com/tiangolo/typer/pull/10).7* Update references to `--install-completion` and `--show-completion` in docs. PR [#9](https://github.com/tiangolo/typer/pull/9).8* Fix testing utilities, add tests for First Steps examples. PR [#8](https://github.com/tiangolo/typer/pull/8).9* Add auto completion options by default when [click-completion](https://github.com/click-contrib/click-completion) is installed: `--install-completion` and `--show-completion`. PR [#7](https://github.com/tiangolo/typer/pull/7).10* Update Termynal to have fixed sizes, add "fast" button, and use it in [First Steps](https://typer.tiangolo.com/tutorial/first-steps/). PR [#6](https://github.com/tiangolo/typer/pull/6).
18 unmodified lines
added:tests/test_tutorial/test_options/__init__.py
added:tests/test_tutorial/test_options/test_tutorial001.py+48 added
1import subprocess23import typer4from typer.testing import CliRunner56from options import tutorial001 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.output19 assert "Last name of person to greet." in result.output20 assert "Say hi formally." in result.output212223def test_1():24 result = runner.invoke(app, ["Camila"])25 assert result.exit_code == 026 assert "Hello Camila" in result.output272829def test_option_lastname():30 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])31 assert result.exit_code == 032 assert "Hello Camila Gutiérrez" in result.output333435def test_formal():36 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez", "--formal"])37 assert result.exit_code == 038 assert "Good day Ms. Camila Gutiérrez." in result.output394041def test_script():42 result = subprocess.run(43 ["coverage", "run", mod.__file__, "--help"],44 stdout=subprocess.PIPE,45 stderr=subprocess.PIPE,46 encoding="utf-8",47 )48 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_tutorial002.py+40 added
1import subprocess23import typer4from typer.testing import CliRunner56from options import tutorial002 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_1():15 result = runner.invoke(app, ["Camila"])16 assert result.exit_code != 017 assert 'Error: Missing option "--lastname".' in result.output181920def test_option_lastname():21 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])22 assert result.exit_code == 023 assert "Hello Camila Gutiérrez" in result.output242526def test_help():27 result = runner.invoke(app, ["--help"])28 assert result.exit_code == 029 assert "--lastname TEXT" in result.output30 assert "[required]" in result.output313233def test_script():34 result = subprocess.run(35 ["coverage", "run", mod.__file__, "--help"],36 stdout=subprocess.PIPE,37 stderr=subprocess.PIPE,38 encoding="utf-8",39 )40 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_tutorial003.py+41 added
1import subprocess23import typer4from typer.testing import CliRunner56from options import tutorial003 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_option_lastname():15 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])16 assert result.exit_code == 017 assert "Hello Camila Gutiérrez" in result.output181920def test_option_lastname_prompt():21 result = runner.invoke(app, ["Camila"], input="Gutiérrez")22 assert result.exit_code == 023 assert "Lastname: " in result.output24 assert "Hello Camila Gutiérrez" in result.output252627def test_help():28 result = runner.invoke(app, ["--help"])29 assert result.exit_code == 030 assert "--lastname TEXT" in result.output31 assert "[required]" in result.output323334def test_script():35 result = subprocess.run(36 ["coverage", "run", mod.__file__, "--help"],37 stdout=subprocess.PIPE,38 stderr=subprocess.PIPE,39 encoding="utf-8",40 )41 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_tutorial004.py+41 added
1import subprocess23import typer4from typer.testing import CliRunner56from options import tutorial004 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_option_lastname():15 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])16 assert result.exit_code == 017 assert "Hello Camila Gutiérrez" in result.output181920def test_option_lastname_prompt():21 result = runner.invoke(app, ["Camila"], input="Gutiérrez")22 assert result.exit_code == 023 assert "Please tell me your last name: " in result.output24 assert "Hello Camila Gutiérrez" in result.output252627def test_help():28 result = runner.invoke(app, ["--help"])29 assert result.exit_code == 030 assert "--lastname TEXT" in result.output31 assert "[required]" in result.output323334def test_script():35 result = subprocess.run(36 ["coverage", "run", mod.__file__, "--help"],37 stdout=subprocess.PIPE,38 stderr=subprocess.PIPE,39 encoding="utf-8",40 )41 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_tutorial005.py+50 added
1import subprocess23import typer4from typer.testing import CliRunner56from options import tutorial005 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_prompt():15 result = runner.invoke(app, input="Old Project\nOld Project\n")16 assert result.exit_code == 017 assert "Deleting project Old Project" in result.output181920def test_prompt_not_equal():21 result = runner.invoke(22 app, input="Old Project\nNew Spice\nOld Project\nOld Project\n"23 )24 assert result.exit_code == 025 assert "Error: the two entered values do not match" in result.output26 assert "Deleting project Old Project" in result.output272829def test_option():30 result = runner.invoke(app, ["--project-name", "Old Project"])31 assert result.exit_code == 032 assert "Deleting project Old Project" in result.output33 assert "Project name: " not in result.output343536def test_help():37 result = runner.invoke(app, ["--help"])38 assert result.exit_code == 039 assert "--project-name TEXT" in result.output40 assert "[required]" in result.output414243def test_script():44 result = subprocess.run(45 ["coverage", "run", mod.__file__, "--help"],46 stdout=subprocess.PIPE,47 stderr=subprocess.PIPE,48 encoding="utf-8",49 )50 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_tutorial006.py+34 added
1import subprocess23import typer4from typer.testing import CliRunner56from options import tutorial006 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_call():15 result = runner.invoke(app)16 assert result.exit_code == 017 assert "Hello Wade Wilson" in result.output181920def test_help():21 result = runner.invoke(app, ["--help"])22 assert result.exit_code == 023 assert "--fullname TEXT" in result.output24 assert "[default: Wade Wilson]" in result.output252627def test_script():28 result = subprocess.run(29 ["coverage", "run", mod.__file__, "--help"],30 stdout=subprocess.PIPE,31 stderr=subprocess.PIPE,32 encoding="utf-8",33 )34 assert "Usage" in result.stdout
modified:typer/completion.py+2 added-1 removed
12 unmodified lines
13def install_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any: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 click.secho(f"{shell} completion installed in {path}.", fg="green")18 click.echo("Completion will take effect once you restart the terminal.")19 sys.exit(0)202122def show_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
26 unmodified lines
modified:typer/main.py+1 added-1 removed
26 unmodified lines
2728try:29 import click_completion30 from .completion import _install_completion_placeholder_function31except ImportError:31except ImportError: # pragma: no cover32 click_completion = None333435def get_install_completion_arguments() -> Tuple[click.Parameter, click.Parameter]:
679 unmodified lines
modified:typer/models.py+1 added-1 removed
12 unmodified lines
13)1415import click1617if TYPE_CHECKING:17if TYPE_CHECKING: # pragma: no cover18 from .main import Typer # noqa192021NoneType = type(None)
365 unmodified lines
modified:mkdocs.yml+1 added
21 unmodified lines
22 - Features: 'features.md'23 - Tutorial - User Guide:24 - Tutorial - User Guide - Intro: 'tutorial/index.md'25 - First Steps: 'tutorial/first-steps.md'26 - CLI Options: 'tutorial/options.md'27 - Alternatives, Inspiration and Comparisons: 'alternatives.md'28 - Help Typer - Get Help: 'help-typer.md'29 - Development - Contributing: 'contributing.md'30 - Release Notes: release-notes.md
34 unmodified lines
modified:README.md+1 added-1 removed
96 unmodified lines
97 --install-completion Install completion for the current shell.98 --show-completion Show completion for the current shell, to copy it or customize the installation.99 --help Show this message and exit.100101// You get a ✨ auto completion ✨ for free, installed with --install-completion101// You get ✨ auto completion ✨ for free, installed with --install-completion102103// Now pass the NAME argument104$ python main.py Camila105
169 unmodified lines