: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
Provenance
- Commit
b434023- Tree
54fa78c- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
5185178- Parent 2
3332ab3
12 files changed+360 added−4 removed
modified:docs/css/custom.css+1 added-1 removed
2 unmodified lines345677892 unmodified lines font-style: italic; display: block;}
.termy {.termy [data-termynal] { white-space: pre-wrap;}modified:docs/css/termynal.css+2 added-1 removed
16 unmodified lines171819202121222324252682 unmodified lines16 unmodified lines max-width: 100%; background: var(--color-bg); color: var(--color-text); font-size: 18px; /* font-family: 'Fira Mono', Consolas, Menlo, Monaco, 'Courier New', Courier, monospace; */ font-family: 'Fira Mono', Consolas, Menlo, Monaco, 'Courier New', Courier, monospace; font-family: 'Roboto Mono', 'Fira Mono', Consolas, Menlo, Monaco, 'Courier New', Courier, monospace; border-radius: 4px; padding: 75px 45px 35px; position: relative; -webkit-box-sizing: border-box;82 unmodified linesmodified:docs/js/termynal.js+2 added-2 removed
133 unmodified lines134 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 lines148 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 linesadded:docs/src/arguments/tutorial001.py+9 added
1+import typer2+3+4+def main(name: str = typer.Argument(...)):5+ typer.echo(f"Hello {name}")6+7+8+if __name__ == "__main__":9+ typer.run(main)added:docs/src/arguments/tutorial002.py+12 added
1+import typer2+3+4+def main(name: str = typer.Argument(None)):5+ if name is None:6+ typer.echo("Hello World!")7+ else:8+ typer.echo(f"Hello {name}")9+10+11+if __name__ == "__main__":12+ typer.run(main)added:docs/src/arguments/tutorial003.py+9 added
1+import typer2+3+4+def main(name: str = typer.Argument("Wade Wilson")):5+ typer.echo(f"Hello {name}")6+7+8+if __name__ == "__main__":9+ typer.run(main)added:docs/tutorial/arguments.md+213 added
1+The 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*.2+3+## Optional *CLI arguments*4+5+We said before that *by default*:6+7+* *CLI options* are **optional**8+* *CLI arguments* are **required**9+10+Again, that's how they work *by default*, and that's the convention in many CLI programs and systems.11+12+But you can change that.13+14+In fact, it's very common to have **optional** *CLI arguments*, it's way more common than having **required** *CLI options*.15+16+As an example of how it could be useful, let's see how the `ls` command works.17+18+<div class="termy">19+20+```console21+// If you just type22+$ ls23+24+// ls will "list" the files and directories in the current directory25+typer tests README.md LICENSE26+27+// But it also receives an optional CLI argument28+$ ls ./tests/29+30+// And then ls will list the files and directories inside of that directory from the CLI argument31+__init__.py test_tutorial32+```33+34+</div>35+36+### An alternative *CLI argument* declaration37+38+In 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*:39+40+```Python hl_lines="4"41+{!./src/first_steps/tutorial002.py!}42+```43+44+Now let's see an alternative way to create the same *CLI argument*:45+46+```Python hl_lines="4"47+{!./src/arguments/tutorial001.py!}48+```49+50+Before you had this function parameter:51+52+```Python53+name: str54+```55+56+And because `name` didn't have any default value it would be a **required parameter** for the Python function, in Python terms.57+58+**Typer** does the same and makes it a **required** *CLI argument*.59+60+And then we changed it to:61+62+```Python63+name: str = typer.Argument(...)64+```65+66+The same as with `typer.Option()`, there is a `typer.Argument()`.67+68+And 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).69+70+As 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.71+72+To make it *required*, we pass `...` as that first parameter to the function.73+74+!!! 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>.76+77+!!! tip78+ This works exactly the same way `typer.Option()` does.79+80+All we did there achieves the same thing as before, a **required** *CLI argument*:81+82+<div class="termy">83+84+```console85+$ python main.py86+87+Usage: main.py [OPTIONS] NAME88+Try "main.py --help" for help.89+90+Error: Missing argument "NAME".91+```92+93+</div>94+95+It's still not very useful, but it works correctly.96+97+And 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.98+99+### Make an optional *CLI argument*100+101+Now, finally what we came for, an optional *CLI argument*.102+103+To make a *CLI argument* optional, use `typer.Argument()` and pass a different "default" as the first parameter to `typer.Argument()`, for example `None`:104+105+```Python hl_lines="4"106+{!./src/arguments/tutorial002.py!}107+```108+109+Now we have:110+111+```Python112+name: str = typer.Argument(None)113+```114+115+Because we are using `typer.Argument()` **Typer** will know that this is a *CLI argument* (no matter if *required* or *optional*).116+117+And 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`.118+119+Check the help:120+121+<div class="termy">122+123+```console124+// First check the help125+$ python main.py --help126+127+Usage: main.py [OPTIONS] [NAME]128+129+Options: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+```134+135+</div>136+137+!!! tip138+ Notice that `NAME` is still a *CLI argument*, it's shown up there in the "`Usage: main.py` ...".139+140+ Also notice that now `[NAME]` has brackets ("`[`" and "`]`") around (before it was just `NAME`) to denote that it's **optional**, not **required**.141+142+Now run it and test it:143+144+<div class="termy">145+146+```console147+// With no CLI argument148+$ python main.py149+150+Hello World!151+152+// With one optional CLI argument153+$ python main.py154+155+Hello Camila156+```157+158+</div>159+160+!!! 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.162+163+## An optional *CLI argument* with a default164+165+We can also make a *CLI argument* have a default value other than `None`:166+167+```Python hl_lines="4"168+{!./src/arguments/tutorial003.py!}169+```170+171+And test it:172+173+<div class="termy">174+175+```console176+// With no optional CLI argument177+$ python main.py178+179+Hello Wade Wilson180+181+// With one CLI argument182+$ python main.py Camila183+184+Hello Camila185+```186+187+</div>188+189+## About *CLI arguments* help190+191+*CLI arguments* are commonly used for the most necessary things in a program.192+193+They are normally required and, when present, they are normally the main subject of whatever the command is doing.194+195+For that reason, Typer (actually Click underneath) doesn't attempt to automatically document *CLI arguments*.196+197+And 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>.198+199+Check the last example from the <a href="https://typer.tiangolo.com/tutorial/first-steps/#document-your-cli-app" target="_blank">First Steps</a>:200+201+```Python hl_lines="5 6 7 8 9"202+{!./src/first_steps/tutorial006.py!}203+```204+205+Here the *CLI argument* `NAME` is documented as part of the command help text.206+207+You should document your *CLI arguments* the same way.208+209+## Other uses210+211+`typer.Argument()` has several other users. For data validation, to enable other features, etc.212+213+But 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
1+import subprocess2+3+import typer4+from typer.testing import CliRunner5+6+from arguments import tutorial001 as mod7+8+runner = CliRunner()9+10+app = typer.Typer()11+app.command()(mod.main)12+13+14+def test_call_no_arg():15+ result = runner.invoke(app)16+ assert result.exit_code != 017+ assert 'Error: Missing argument "NAME".' in result.output18+19+20+def test_call_arg():21+ result = runner.invoke(app, ["Camila"])22+ assert result.exit_code == 023+ assert "Hello Camila" in result.output24+25+26+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_tutorial002.py+39 added
1+import subprocess2+3+import typer4+from typer.testing import CliRunner5+6+from arguments import tutorial002 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 "[OPTIONS] [NAME]" in result.output18+19+20+def test_call_no_arg():21+ result = runner.invoke(app)22+ assert result.exit_code == 023+ assert "Hello World!" in result.output24+25+26+def test_call_arg():27+ result = runner.invoke(app, ["Camila"])28+ assert result.exit_code == 029+ assert "Hello Camila" in result.output30+31+32+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_tutorial003.py+39 added
1+import subprocess2+3+import typer4+from typer.testing import CliRunner5+6+from arguments import tutorial003 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 "[OPTIONS] [NAME]" in result.output18+19+20+def test_call_no_arg():21+ result = runner.invoke(app)22+ assert result.exit_code == 023+ assert "Hello Wade Wilson" in result.output24+25+26+def test_call_arg():27+ result = runner.invoke(app, ["Camila"])28+ assert result.exit_code == 029+ assert "Hello Camila" in result.output30+31+32+def 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.stdoutmodified:mkdocs.yml+1 added
22 unmodified lines23 - 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.md34 unmodified lines