Skip to content
Myr

:memo: Add docs for CLI arguments

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 5185178, 3332ab3 · Browse files · 12 files+360 added−4 removed
This commit

State

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

Diff stats

12 files+360 added−4 removed

  • tests:+111 added−0 removed
  • other:+249 added−4 removed

12 files+360 added−4 removed

modified:docs/css/custom.css+1 added-1 removed
modified:docs/css/termynal.css+2 added-1 removed
modified:docs/js/termynal.js+2 added-2 removed
133 unmodified lines
134 this.init()135 }136 restart.href = '#'137 restart.setAttribute('data-terminal-control', '')138 restart.innerHTML = "restart \u27f3" // Refresh emoji138 restart.innerHTML = "restart ↻"139 return restart140 }141 142 generateFinish() {
5 unmodified lines
148 this.startDelay = 0149 }150 finish.href = '#'151 finish.setAttribute('data-terminal-control', '')152 finish.innerHTML = "fast \u2b95" // Fast emoji arrow152 finish.innerHTML = "fast →"153 this.finishElement = finish154 return finish155 }156
108 unmodified lines
added:docs/src/arguments/tutorial001.py+9 added
1import typer234def main(name: str = typer.Argument(...)):5 typer.echo(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/arguments/tutorial002.py+12 added
1import typer234def main(name: str = typer.Argument(None)):5 if name is None:6 typer.echo("Hello World!")7 else:8 typer.echo(f"Hello {name}")91011if __name__ == "__main__":12 typer.run(main)
added:docs/src/arguments/tutorial003.py+9 added
1import typer234def main(name: str = typer.Argument("Wade Wilson")):5 typer.echo(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
added:docs/tutorial/arguments.md+213 added
1The same way that you have `typer.Option()` to help you define things for *CLI options*, there's also the equivalent `typer.Argument()` for *CLI arguments*.23## Optional *CLI arguments*45We said before that *by default*:67* *CLI options* are **optional**8* *CLI arguments* are **required**910Again, that's how they work *by default*, and that's the convention in many CLI programs and systems.1112But you can change that.1314In fact, it's very common to have **optional** *CLI arguments*, it's way more common than having **required** *CLI options*.1516As an example of how it could be useful, let's see how the `ls` command works.1718<div class="termy">1920```console21// If you just type22$ ls2324// ls will "list" the files and directories in the current directory25typer tests README.md LICENSE2627// But it also receives an optional CLI argument28$ ls ./tests/2930// And then ls will list the files and directories inside of that directory from the CLI argument31__init__.py test_tutorial32```3334</div>3536### An alternative *CLI argument* declaration3738In the <a href="https://typer.tiangolo.com/tutorial/first-steps/#add-a-cli-argument" target="_blank">First Steps</a> you saw how to add a *CLI argument*:3940```Python hl_lines="4"41{!./src/first_steps/tutorial002.py!}42```4344Now let's see an alternative way to create the same *CLI argument*:4546```Python hl_lines="4"47{!./src/arguments/tutorial001.py!}48```4950Before you had this function parameter:5152```Python53name: str54```5556And because `name` didn't have any default value it would be a **required parameter** for the Python function, in Python terms.5758**Typer** does the same and makes it a **required** *CLI argument*.5960And then we changed it to:6162```Python63name: str = typer.Argument(...)64```6566The same as with `typer.Option()`, there is a `typer.Argument()`.6768And now as `typer.Argument()` is the "default value" of the function's parameter, in Python terms, it would mean that "it is no longer required" (in Python terms).6970As we no longer have the Python function default value (or its absence) to tell it if something is required or not and what is the default value, the first parameter to `typer.Argument()` serves the same purpose of defining that default value, or making it required.7172To make it *required*, we pass `...` as that first parameter to the function.7374!!! info75 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>.7677!!! tip78 This works exactly the same way `typer.Option()` does.7980All we did there achieves the same thing as before, a **required** *CLI argument*:8182<div class="termy">8384```console85$ python main.py8687Usage: main.py [OPTIONS] NAME88Try "main.py --help" for help.8990Error: Missing argument "NAME".91```9293</div>9495It's still not very useful, but it works correctly.9697And being able to declare a **required** *CLI argument* using `name: str = typer.Argument(...)` that works exactly the same as `name: str` will come handy later.9899### Make an optional *CLI argument*100101Now, finally what we came for, an optional *CLI argument*.102103To make a *CLI argument* optional, use `typer.Argument()` and pass a different "default" as the first parameter to `typer.Argument()`, for example `None`:104105```Python hl_lines="4"106{!./src/arguments/tutorial002.py!}107```108109Now we have:110111```Python112name: str = typer.Argument(None)113```114115Because we are using `typer.Argument()` **Typer** will know that this is a *CLI argument* (no matter if *required* or *optional*).116117And because the first parameter passed to `typer.Argument(None)` (the new "default" value) is `None`, **Typer** knows that this is an **optional** *CLI argument*, if no value is provided when calling it in the command line, it will have that default value of `None`.118119Check the help:120121<div class="termy">122123```console124// First check the help125$ python main.py --help126127Usage: main.py [OPTIONS] [NAME]128129Options:130 --install-completion Install completion for the current shell.131 --show-completion Show completion for the current shell, to copy it or customize the installation.132 --help Show this message and exit.133```134135</div>136137!!! tip138 Notice that `NAME` is still a *CLI argument*, it's shown up there in the "`Usage: main.py` ...".139140 Also notice that now `[NAME]` has brackets ("`[`" and "`]`") around (before it was just `NAME`) to denote that it's **optional**, not **required**.141142Now run it and test it:143144<div class="termy">145146```console147// With no CLI argument148$ python main.py149150Hello World!151152// With one optional CLI argument153$ python main.py154155Hello Camila156```157158</div>159160!!! tip161 Notice that "`Camila`" here is an optional *CLI argument*, not a *CLI option*, because we didn't use something like "`--name Camila`", we just passed "`Camila`" directly to the program/command.162163## An optional *CLI argument* with a default164165We can also make a *CLI argument* have a default value other than `None`:166167```Python hl_lines="4"168{!./src/arguments/tutorial003.py!}169```170171And test it:172173<div class="termy">174175```console176// With no optional CLI argument177$ python main.py178179Hello Wade Wilson180181// With one CLI argument182$ python main.py Camila183184Hello Camila185```186187</div>188189## About *CLI arguments* help190191*CLI arguments* are commonly used for the most necessary things in a program.192193They are normally required and, when present, they are normally the main subject of whatever the command is doing.194195For that reason, Typer (actually Click underneath) doesn't attempt to automatically document *CLI arguments*.196197And you should document them as part of the command documentation, normally in a <abbr title="a multi-line string as the first expression inside a function (not assigned to any variable) used for documentation">docstring</abbr>.198199Check the last example from the <a href="https://typer.tiangolo.com/tutorial/first-steps/#document-your-cli-app" target="_blank">First Steps</a>:200201```Python hl_lines="5 6 7 8 9"202{!./src/first_steps/tutorial006.py!}203```204205Here the *CLI argument* `NAME` is documented as part of the command help text.206207You should document your *CLI arguments* the same way.208209## Other uses210211`typer.Argument()` has several other users. For data validation, to enable other features, etc.212213But you will see about that later in the docs.
added:tests/test_tutorial/test_arguments/__init__.py
added:tests/test_tutorial/test_arguments/test_tutorial001.py+33 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments import tutorial001 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_call_no_arg():15 result = runner.invoke(app)16 assert result.exit_code != 017 assert 'Error: Missing argument "NAME".' in result.output181920def test_call_arg():21 result = runner.invoke(app, ["Camila"])22 assert result.exit_code == 023 assert "Hello Camila" in result.output242526def test_script():27 result = subprocess.run(28 ["coverage", "run", mod.__file__, "--help"],29 stdout=subprocess.PIPE,30 stderr=subprocess.PIPE,31 encoding="utf-8",32 )33 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_tutorial002.py+39 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments import tutorial002 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 "[OPTIONS] [NAME]" in result.output181920def test_call_no_arg():21 result = runner.invoke(app)22 assert result.exit_code == 023 assert "Hello World!" in result.output242526def test_call_arg():27 result = runner.invoke(app, ["Camila"])28 assert result.exit_code == 029 assert "Hello Camila" in result.output303132def test_script():33 result = subprocess.run(34 ["coverage", "run", mod.__file__, "--help"],35 stdout=subprocess.PIPE,36 stderr=subprocess.PIPE,37 encoding="utf-8",38 )39 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_tutorial003.py+39 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments import tutorial003 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 "[OPTIONS] [NAME]" in result.output181920def test_call_no_arg():21 result = runner.invoke(app)22 assert result.exit_code == 023 assert "Hello Wade Wilson" in result.output242526def test_call_arg():27 result = runner.invoke(app, ["Camila"])28 assert result.exit_code == 029 assert "Hello Camila" in result.output303132def test_script():33 result = subprocess.run(34 ["coverage", "run", mod.__file__, "--help"],35 stdout=subprocess.PIPE,36 stderr=subprocess.PIPE,37 encoding="utf-8",38 )39 assert "Usage" in result.stdout
modified:mkdocs.yml+1 added
22 unmodified lines
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 - CLI Arguments: 'tutorial/arguments.md'28 - Alternatives, Inspiration and Comparisons: 'alternatives.md'29 - Help Typer - Get Help: 'help-typer.md'30 - Development - Contributing: 'contributing.md'31 - Release Notes: release-notes.md
34 unmodified lines