Skip to content
Myr

✨ Add support for help for CLI arguments (#123)

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

* ✨ Implement custom TyperCommand and TyperArgument to support help in CLI Arguments * ✨ Update data models to store help for CLI Arguments * ✨ Add help to typer.Argument() * ✨ Use new TyperCommand and TyperArgument classes by default to support CLI Arguments with help * ✅ Update failing test * ✨ Make showing default values default to true and support arguments hidden from help text * ✨ Add docs for CLI arguments with defaults, help, and new features * 📝 Update CLI options with new show_default=True by default * 📝 Add example of CLI arguments with tuples * 📝 Update docs with new generated help text for CLI arguments * 📝 Use Optional for None example in micro-intro to types * ✅ Add tests for new CLI argument features from docs examples * ✅ Update tests with new generated help text for CLI arguments * ✅ Add tests for CLI arguments with tuple defaults * 🔧 Update MkDocs with new sections * ✨ make show_envvar default to True * ✨ Add docs for envvar in CLI arguments * ✅ Add tests for CLI arguments with env vars from docs * 🎨 Add format to CLI usage examples in docs * 🔧 Add section about CLI arguments with env vars to MkDocs * 📝 Fix link in docs with new structure * 🎨 Fix format in first-steps

authored by Sebastián Ramírez · committed by GitHub · parent 338d05f · Browse files · 64 files+1749 added−400 removed
This commit

State

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

Diff stats

64 files+1749 added−400 removed

  • tests:+620 added−113 removed
  • other:+1129 added−287 removed

64 files+1749 added−400 removed

added:docs/src/arguments/default/tutorial001.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/src/arguments/default/tutorial002.py+15 added
1import random23import typer456def get_name():7 return random.choice(["Deadpool", "Rick", "Morty", "Hiro"])8910def main(name: str = typer.Argument(get_name)):11 typer.echo(f"Hello {name}")121314if __name__ == "__main__":15 typer.run(main)
added:docs/src/arguments/envvar/tutorial001.py+9 added
1import typer234def main(name: str = typer.Argument("World", envvar="AWESOME_NAME")):5 typer.echo(f"Hello Mr. {name}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/arguments/envvar/tutorial002.py+9 added
1import typer234def main(name: str = typer.Argument("World", envvar=["AWESOME_NAME", "GOD_NAME"])):5 typer.echo(f"Hello Mr. {name}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/arguments/envvar/tutorial003.py+9 added
1import typer234def main(name: str = typer.Argument("World", envvar="AWESOME_NAME", show_envvar=False)):5 typer.echo(f"Hello Mr. {name}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/arguments/help/tutorial001.py+9 added
1import typer234def main(name: str = typer.Argument(..., help="The name of the user to greet")):5 typer.echo(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/arguments/help/tutorial002.py+12 added
1import typer234def main(name: str = typer.Argument(..., help="The name of the user to greet")):5 """6 Say hi to NAME very gently, like Dirk.7 """8 typer.echo(f"Hello {name}")91011if __name__ == "__main__":12 typer.run(main)
added:docs/src/arguments/help/tutorial003.py+12 added
1import typer234def main(name: str = typer.Argument("World", help="Who to greet")):5 """6 Say hi to NAME very gently, like Dirk.7 """8 typer.echo(f"Hello {name}")91011if __name__ == "__main__":12 typer.run(main)
added:docs/src/arguments/help/tutorial004.py+12 added
1import typer234def main(name: str = typer.Argument("World", help="Who to greet", show_default=False)):5 """6 Say hi to NAME very gently, like Dirk.7 """8 typer.echo(f"Hello {name}")91011if __name__ == "__main__":12 typer.run(main)
added:docs/src/arguments/help/tutorial005.py+13 added
1import typer234def main(5 name: str = typer.Argument(6 "Wade Wilson", help="Who to greet", show_default="Deadpoolio the amazing's name"7 )8):9 typer.echo(f"Hello {name}")101112if __name__ == "__main__":13 typer.run(main)
added:docs/src/arguments/help/tutorial006.py+9 added
1import typer234def main(name: str = typer.Argument("World", metavar="✨username✨")):5 typer.echo(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/arguments/help/tutorial007.py+12 added
1import typer234def main(name: str = typer.Argument("World", hidden=True)):5 """6 Say hi to NAME very gently, like Dirk.7 """8 typer.echo(f"Hello {name}")91011if __name__ == "__main__":12 typer.run(main)
added:docs/src/arguments/optional/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/optional/tutorial002.py+14 added
1from typing import Optional23import typer456def main(name: Optional[str] = typer.Argument(None)):7 if name is None:8 typer.echo("Hello World!")9 else:10 typer.echo(f"Hello {name}")111213if __name__ == "__main__":14 typer.run(main)
deleted:docs/src/arguments/tutorial001.py-9 removed
1import typer234def main(name: str = typer.Argument(...)):5 typer.echo(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
deleted:docs/src/arguments/tutorial002.py-12 removed
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)
deleted:docs/src/arguments/tutorial003.py-9 removed
1import typer234def main(name: str = typer.Argument("Wade Wilson")):5 typer.echo(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/multiple_values/arguments_with_multiple_values/tutorial002.py+16 added
1from typing import Tuple23import typer456def main(7 names: Tuple[str, str, str] = typer.Argument(8 ("Harry", "Hermione", "Ron"), help="Select 3 characters to play with"9 )10):11 for name in names:12 typer.echo(f"Hello {name}")131415if __name__ == "__main__":16 typer.run(main)
modified:docs/src/options/help/tutorial002.py+1 added-1 removed
1import typer234def main(fullname: str = typer.Option("Wade Wilson", show_default=True)):4def main(fullname: str = typer.Option("Wade Wilson", show_default=False)):5 typer.echo(f"Hello {fullname}")678if __name__ == "__main__":
1 unmodified line
added:docs/tutorial/arguments/default.md+99 added
1We can also use the same `typer.Argument()` to set a default value.23That way the *CLI argument* will be optional *and also* have a default value.45## An optional *CLI argument* with a default67We can also use `typer.Argument()` to make a *CLI argument* have a default value other than `None`:89```Python hl_lines="4"10{!./src/arguments/default/tutorial001.py!}11```1213!!! tip14 Because now the value will be a `str` passed by the user or the default value of `"Wade Wilson"` which is also a `str`, we know the value will never be `None`, so we don't have to (and shouldn't) use `Optional[str]`.1516 Have in mind that the `Optional[something]` tells Python that a value "could be `None`". But the use of `Optional` doesn't affect Typer in any way, e.g. it doesn't tell Typer if a value is required or not.1718Check it:1920<div class="termy">2122```console23// Check the help24$ python main.py --help2526// Notice the [default: Wade Wilson] ✨27Usage: main.py [OPTIONS] [NAME]2829Arguments:30 [NAME] [default: Wade Wilson]3132Options:33 --install-completion Install completion for the current shell.34 --show-completion Show completion for the current shell, to copy it or customize the installation.35 --help Show this message and exit.3637// With no optional CLI argument38$ python main.py3940Hello Wade Wilson4142// With one CLI argument43$ python main.py Camila4445Hello Camila46```4748</div>4950## Dynamic default value5152And we can even make the default value be dynamically generated by passing a function as the first function argument:5354```Python hl_lines="6 7 10"55{!./src/arguments/default/tutorial002.py!}56```5758In this case, we created the function `get_name` that will just return a random `str` each time.5960And we pass it as the first function argument to `typer.Argument()`.6162Check it:6364<div class="termy">6566```console67// Check the help68$ python main.py --help6970Usage: main.py [OPTIONS] [NAME]7172Arguments:73 [NAME] [default: (dynamic)]7475Options:76 --install-completion Install completion for the current shell.77 --show-completion Show completion for the current shell, to copy it or customize the installation.78 --help Show this message and exit.7980// Try it several times, it will use a random default each time81$ python main.py8283Hello Deadpool8485$ python main.py8687Hello Hiro8889$ python main.py9091Hello Rick9293// Now pass a value for the CLI argument94$ python main.py Camila9596Hello Camila97```9899</div>
added:docs/tutorial/arguments/envvar.md+127 added
1You can also configure a *CLI argument* to read a value from an environment variable if it is not provided in the command line as a *CLI argument*.23To do that, use the `envvar` parameter for `typer.Argument()`:45```Python hl_lines="4"6{!./src/arguments/envvar/tutorial001.py!}7```89In this case, the *CLI argument* `name` will have a default value of `"World"`, but will also read any value passed to the environment variable `AWESOME_NAME` if no value is provided in the command line:1011<div class="termy">1213```console14// Check the help15$ python main.py --help1617Usage: main.py [OPTIONS] [NAME]1819Arguments:20 [NAME] [env var: AWESOME_NAME;default: World]2122Options:23 --install-completion Install completion for the current shell.24 --show-completion Show completion for the current shell, to copy it or customize the installation.25 --help Show this message and exit.2627// Call it without a CLI argument28$ python main.py2930Hello Mr. World3132// Now pass a value for the CLI argument33$ python main.py Czernobog3435Hello Mr. Czernobog3637// And now use the environment variable38$ AWESOME_NAME=Wednesday python main.py3940Hello Mr. Wednesday4142// CLI arguments take precedence over env vars43$ AWESOME_NAME=Wednesday python main.py Czernobog4445Hello Mr. Czernobog46```4748</div>4950## Multiple environment variables5152You are not restricted to a single environment variable, you can declare a list of environment variables that could be used to get a value if it was not passed in the command line:5354```Python hl_lines="4"55{!./src/arguments/envvar/tutorial002.py!}56```5758Check it:5960<div class="termy">6162```console63// Check the help64$ python main.py --help6566Usage: main.py [OPTIONS] [NAME]6768Arguments:69 [NAME] [env var: AWESOME_NAME, GOD_NAME;default: World]7071Options:72 --install-completion Install completion for the current shell.73 --show-completion Show completion for the current shell, to copy it or customize the installation.74 --help Show this message and exit.7576// Try the first env var77$ AWESOME_NAME=Wednesday python main.py7879Hello Mr. Wednesday8081// Try the second env var82$ GOD_NAME=Anubis python main.py8384Hello Mr. Anubis85```8687</div>8889## Hide an env var from the help text9091By default, environment variables used will be shown in the help text, but you can disable them with `show_envvar=False`:9293```Python hl_lines="4"94{!../docs/src/arguments/envvar/tutorial003.py!}95```9697Check it:9899<div class="termy">100101```console102//Check the help103$ python main.py --help104105// It won't show the env var106Usage: main.py [OPTIONS] [NAME]107108Arguments:109 [NAME] [default: World]110111Options:112 --install-completion Install completion for the current shell.113 --show-completion Show completion for the current shell, to copy it or customize the installation.114 --help Show this message and exit.115116// But it will still be able to use it117$ AWESOME_NAME=Wednesday python main.py118119Hello Mr. Wednesday120```121122</div>123124!!! note "Technical Details"125 In Click applications the env vars are hidden by default. 🙈126127 In **Typer** these env vars are shown by default. 👀
added:docs/tutorial/arguments/help.md+270 added
1In 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>.23Here's how that last example looked like:45```Python6{!./src/first_steps/tutorial006.py!}7```89Now that you also know how to use `typer.Argument()`, let's use it to add documentation specific for a *CLI argument*.1011## Add a `help` text for a *CLI argument*1213You can use the `help` parameter to add a help text for a *CLI argument*:1415```Python hl_lines="4"16{!../docs/src/arguments/help/tutorial001.py!}17```1819And it will be used in the automatic `--help` option:2021<div class="termy">2223```console24$ python main.py --help2526// Check the section with Arguments below 🚀27Usage: main.py [OPTIONS] NAME2829Arguments:30 NAME The name of the user to greet [required]3132Options:33 --install-completion Install completion for the current shell.34 --show-completion Show completion for the current shell, to copy it or customize the installation.35 --help Show this message and exit.36```3738</div>3940## Combine help text and docstrings4142And of course, you can also combine that `help` with the <abbr title="a multi-line string as the first expression inside a function (not assigned to any variable) used for documentation">docstring</abbr>:4344```Python hl_lines="4 5 6 7"45{!../docs/src/arguments/help/tutorial002.py!}46```4748And the `--help` option will combine all the information:4950<div class="termy">5152```console53$ python main.py --help5455// Notice that we have the help text from the docstring and also the Arguments 📝56Usage: main.py [OPTIONS] NAME5758 Say hi to NAME very gently, like Dirk.5960Arguments:61 NAME The name of the user to greet [required]6263Options:64 --install-completion Install completion for the current shell.65 --show-completion Show completion for the current shell, to copy it or customize the installation.66 --help Show this message and exit.67```6869</div>7071## Help with defaults7273If you have a *CLI argument* with a default value, like `"World"`:7475```Python hl_lines="4"76{!../docs/src/arguments/help/tutorial003.py!}77```7879It will show that default value in the help text:8081<div class="termy">8283```console84$ python main.py --help8586// Notice the [default: World] 🔍87Usage: main.py [OPTIONS] [NAME]8889 Say hi to NAME very gently, like Dirk.9091Arguments:92 [NAME] Who to greet [default: World]9394Options:95 --install-completion Install completion for the current shell.96 --show-completion Show completion for the current shell, to copy it or customize the installation.97 --help Show this message and exit.98```99100</div>101102But you can disable that if you want to, with `show_default=False`:103104```Python hl_lines="4"105{!../docs/src/arguments/help/tutorial004.py!}106```107108And then it won't show the default value:109110<div class="termy">111112```console113$ python main.py --help114115// Notice the there's no [default: World] now 🔥116Usage: main.py [OPTIONS] [NAME]117118 Say hi to NAME very gently, like Dirk.119120Arguments:121 [NAME] Who to greet122123Options:124 --install-completion Install completion for the current shell.125 --show-completion Show completion for the current shell, to copy it or customize the installation.126127 --help Show this message and exit.128```129130</div>131132!!! note "Technical Details"133 In Click applications the default values are hidden by default. 🙈134135 In **Typer** these default values are shown by default. 👀136137## Custom default string138139You can use the same `show_default` to pass a custom string (instead of a `bool`) to customize the default value to be shown in the help text:140141```Python hl_lines="6"142{!../docs/src/arguments/help/tutorial005.py!}143```144145And it will be used in the help text:146147<div class="termy">148149```console150$ python main.py --help151152Usage: main.py [OPTIONS] [NAME]153154Arguments:155 [NAME] Who to greet [default: (Deadpoolio the amazing's name)]156157158Options:159 --install-completion Install completion for the current shell.160 --show-completion Show completion for the current shell, to copy it or customize the installation.161 --help Show this message and exit.162163// See it shows "(Deadpoolio the amazing's name)" instead of the actual default of "Wade Wilson"164```165166</div>167168## Custom help name (`metavar`)169170You can also customize the text used in the generated help text to represent a *CLI argument*.171172By default, it will be the same name you declared, in uppercase letters.173174So, if you declare it as:175176```Python177name: str178```179180It will be shown as:181182```183NAME184```185186But you can customize it with the `metavar` parameter for `typer.Argument()`.187188For example, let's say you don't want to have the default of `NAME`, you want to have `username`, in lowercase, and you really want ✨ emojis ✨ everywhere:189190```Python hl_lines="4"191{!../docs/src/arguments/help/tutorial006.py!}192```193194Now the generated help text will have `✨username✨` instead of `NAME`:195196<div class="termy">197198```console199$ python main.py --help200201Usage: main.py [OPTIONS] ✨username✨202203Arguments:204 ✨username✨ [default: World]205206Options:207 --install-completion Install completion for the current shell.208 --show-completion Show completion for the current shell, to copy it or customize the installation.209 --help Show this message and exit.210```211212</div>213214## Hide a *CLI argument* from the help text215216If you want, you can make a *CLI argument* **not** show up in the `Arguments` section in the help text.217218You will probably not want to do this normally, but it's possible:219220```Python hl_lines="4"221{!../docs/src/arguments/help/tutorial007.py!}222```223224Check it:225226<div class="termy">227228```console229$ python main.py --help230231// Notice there's no Arguments section at all 🔥232Usage: main.py [OPTIONS] [NAME]233234 Say hi to NAME very gently, like Dirk.235236Options:237 --install-completion Install completion for the current shell.238 --show-completion Show completion for the current shell, to copy it or customize the installation.239 --help Show this message and exit.240```241242</div>243244!!! info245 Have in mind that the *CLI argument* will still show up in the first line with `Usage`.246247 But it won't show up in the main help text under the `Arguments` section.248249### Help text for *CLI arguments* in Click250251Click itself doesn't support adding help for *CLI arguments*, and it doesn't generate help for them as in the "`Arguments:`" sections in the examples above.252253Not supporting `help` in *CLI arguments* is an intentional <a href="https://click.palletsprojects.com/en/7.x/documentation/#documenting-arguments" class="external-link" target="_blank">design decision in Click</a>:254255> This is to follow the general convention of Unix tools of using arguments for only the most necessary things, and to document them in the command help text by referring to them by name.256257So, in Click applications, you are expected to write all the documentation for *CLI arguments* by hand in the <abbr title="a multi-line string as the first expression inside a function (not assigned to any variable) used for documentation">docstring</abbr>.258259---260261Nevertheless, **Typer supports `help` for *CLI arguments***. ✨ 🤷‍♂262263**Typer** doesn't follow that convention and instead supports `help` to make it easier to have consistent help texts with a consistent format for your CLI programs. 🎨264265This is also to help you create CLI programs that are ✨ awesome ✨ *by default*. With very little code.266267If you want to keep Click's convention in a **Typer** app, you can do it with the `hidden` parameter as described above.268269!!! note "Technical Details"270 To support `help` in *CLI arguments* **Typer** does a lot of internal work in its own sub-classes of Click's internal classes.
added:docs/tutorial/arguments/index.md+3 added
1In the next few sections we'll see some ways to modify how *CLI arguments* work.23We'll create optional *CLI arguments*, we'll add integrated help for *CLI arguments*, etc.
added:docs/tutorial/arguments/optional.md+158 added
1We said before that *by default*:23* *CLI options* are **optional**4* *CLI arguments* are **required**56Again, that's how they work *by default*, and that's the convention in many CLI programs and systems.78But you can change that.910In fact, it's very common to have **optional** *CLI arguments*, it's way more common than having **required** *CLI options*.1112As an example of how it could be useful, let's see how the `ls` CLI program works.1314<div class="termy">1516```console17// If you just type18$ ls1920// ls will "list" the files and directories in the current directory21typer tests README.md LICENSE2223// But it also receives an optional CLI argument24$ ls ./tests/2526// And then ls will list the files and directories inside of that directory from the CLI argument27__init__.py test_tutorial28```2930</div>3132### An alternative *CLI argument* declaration3334In the [First Steps](../first-steps.md#add-a-cli-argument){.internal-link target=_blank} you saw how to add a *CLI argument*:3536```Python hl_lines="4"37{!./src/first_steps/tutorial002.py!}38```3940Now let's see an alternative way to create the same *CLI argument*:4142```Python hl_lines="4"43{!./src/arguments/optional/tutorial001.py!}44```4546Before, you had this function parameter:4748```Python49name: str50```5152And because `name` didn't have any default value it would be a **required parameter** for the Python function, in Python terms.5354**Typer** does the same and makes it a **required** *CLI argument*.5556And then we changed it to:5758```Python59name: str = typer.Argument(...)60```6162But now as `typer.Argument()` is the "default value" of the function's parameter, it would mean that "it is no longer required" (in Python terms).6364As we no longer have the Python function default value (or its absence) to tell 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.6566To make it *required*, we pass `...` as the first function argument passed to `typer.Argument(...)`.6768!!! info69 If you hadn't seen that `...` before: it is a special single value, it is <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">part of Python and is called "Ellipsis"</a>.7071All we did there achieves the same thing as before, a **required** *CLI argument*:7273<div class="termy">7475```console76$ python main.py7778Usage: main.py [OPTIONS] NAME79Try "main.py --help" for help.8081Error: Missing argument 'NAME'.82```8384</div>8586It's still not very useful, but it works correctly.8788And 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.8990### Make an optional *CLI argument*9192Now, finally what we came for, an optional *CLI argument*.9394To make a *CLI argument* optional, use `typer.Argument()` and pass a different "default" as the first parameter to `typer.Argument()`, for example `None`:9596```Python hl_lines="6"97{!./src/arguments/optional/tutorial002.py!}98```99100Now we have:101102```Python103name: Optional[str] = typer.Argument(None)104```105106Because we are using `typer.Argument()` **Typer** will know that this is a *CLI argument* (no matter if *required* or *optional*).107108And 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`.109110!!! tip111 By using `Optional` your editor will be able to know that the value *could* be `None`, and will be able to warn you if you do something assuming it is a `str` that would break if it was `None`.112113Check the help:114115<div class="termy">116117```console118// First check the help119$ python main.py --help120121Usage: main.py [OPTIONS] [NAME]122123Arguments:124 [NAME]125126Options:127 --install-completion Install completion for the current shell.128 --show-completion Show completion for the current shell, to copy it or customize the installation.129 --help Show this message and exit.130```131132</div>133134!!! tip135 Notice that `NAME` is still a *CLI argument*, it's shown up there in the "`Usage: main.py` ...".136137 Also notice that now `[NAME]` has brackets ("`[`" and "`]`") around (before it was just `NAME`) to denote that it's **optional**, not **required**.138139Now run it and test it:140141<div class="termy">142143```console144// With no CLI argument145$ python main.py146147Hello World!148149// With one optional CLI argument150$ python main.py Camila151152Hello Camila153```154155</div>156157!!! tip158 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.
added:docs/tutorial/arguments/other-uses.md+3 added
1`typer.Argument()` has several other use cases. Such as for data validation, to enable other features, etc.23You will see about these use cases later in the docs.
modified:docs/tutorial/multiple-values/arguments-with-multiple-values.md+48 added
24 unmodified lines
25 We also declared a final *CLI argument* `celebration`, and it's correctly used even if we pass an arbitrary number of `files` first.2627!!! info28 A `List` can only be used in the last command (if there are subcommands), as this will take anything to the right and assume it's part of the expected *CLI arguments*.2930## *CLI arguments* with tuples3132If you want a specific number of values and types, you can use a tuple, and it can even have default values:3334```Python hl_lines="7 8"35{!./src/multiple_values/arguments_with_multiple_values/tutorial002.py!}36```3738Check it:3940<div class="termy">4142```console43// Check the help44$ python main.py --help4546Usage: main.py [OPTIONS] [NAMES]...4748Arguments:49 [NAMES]... [default: Harry, Hermione, Ron]5051Options:52 --install-completion Install completion for the current shell.53 --show-completion Show completion for the current shell, to copy it or customize the installation.54 --help Show this message and exit.5556// Use it with its defaults57$ python main.py5859Hello Harry60Hello Hermione61Hello Ron6263// If you pass an invalid number of arguments you will get an error64$ python main.py Draco Hagrid6566Error: argument names takes 3 values6768// And if you pass the exact number of values it will work correctly69$ python main.py Draco Hagrid Dobby7071Hello Draco72Hello Hagrid73Hello Dobby74```7576</div>
modified:docs/tutorial/options/help.md+17 added-16 removed
1In 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>.1You already saw how to add a help text for *CLI arguments* with the `help` parameter.23Here's how that last example looked like:3Let's now do the same for *CLI options*:45```Python6{!./src/first_steps/tutorial006.py!}7```89Now we'll add a *help* section to the *CLI options*:105```Python hl_lines="6 7"6{!./src/options/help/tutorial001.py!}7```8
37 unmodified lines
46 Say hi to NAME, optionally with a --lastname.4748 If --formal is used, say hi very formally.4950Arguments:51 NAME [required]5253Options:57 --lastname TEXT Last name of person to greet.58 --formal / --no-formal Say hi formally.54 --lastname TEXT Last name of person to greet. [default: ]55 --formal / --no-formal Say hi formally. [default: False]56 --install-completion Install completion for the current shell.57 --show-completion Show completion for the current shell, to copy it or customize the installation.58 --help Show this message and exit.59
1 unmodified line
61```6263</div>6468## Show default in help65## Hide default from help6670You can tell Typer to show the default value in the help text with `show_default=True`:67You can tell Typer to not show the default value in the help text with `show_default=False`:6869```Python hl_lines="4"70{!./src/options/help/tutorial002.py!}71```7276And it will show up in the help text:73And it will no longer show the default value in the help text:7475<div class="termy">7677```console
6 unmodified lines
8485Usage: main.py [OPTIONS]8687Options:91 --fullname TEXT [default: Wade Wilson]88 --fullname TEXT89 --install-completion Install completion for the current shell.90 --show-completion Show completion for the current shell, to copy it or customize the installation.91 --help Show this message and exit.9293// Notice there's no [default: Wade Wilson] 🔥94```9596</div>9799!!! tip100 Notice the `[default: Wade Wilson]` in the help text.98!!! note "Technical Details"99 In Click applications the default values are hidden by default. 🙈100101 In **Typer** these default values are shown by default. 👀
modified:docs/tutorial/subcommands/name-and-help.md-1 removed
251 unmodified lines
252// Check the main help253$ python main.py --help254255// Check the command new-users and its help text256256Usage: main.py [OPTIONS] COMMAND [ARGS]...257258Options:259 --install-completion Install completion for the current shell.
203 unmodified lines
deleted:docs/tutorial/arguments.md-208 removed
1Let's see how to configure *CLI arguments* with `typer.Argument()`.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` CLI program 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 [First Steps](first-steps.md#add-a-cli-argument){.internal-link target=_blank} 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```6566But now as `typer.Argument()` is the "default value" of the function's parameter, it would mean that "it is no longer required" (in Python terms).6768As we no longer have the Python function default value (or its absence) to tell 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.6970To make it *required*, we pass `...` as the first function argument passed to `typer.Argument(...)`.7172!!! info73 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" class="external-link" target="_blank">part of Python and is called "Ellipsis"</a>.7475All we did there achieves the same thing as before, a **required** *CLI argument*:7677<div class="termy">7879```console80$ python main.py8182Usage: main.py [OPTIONS] NAME83Try "main.py --help" for help.8485Error: Missing argument 'NAME'.86```8788</div>8990It's still not very useful, but it works correctly.9192And 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.9394### Make an optional *CLI argument*9596Now, finally what we came for, an optional *CLI argument*.9798To make a *CLI argument* optional, use `typer.Argument()` and pass a different "default" as the first parameter to `typer.Argument()`, for example `None`:99100```Python hl_lines="4"101{!./src/arguments/tutorial002.py!}102```103104Now we have:105106```Python107name: str = typer.Argument(None)108```109110Because we are using `typer.Argument()` **Typer** will know that this is a *CLI argument* (no matter if *required* or *optional*).111112And 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`.113114Check the help:115116<div class="termy">117118```console119// First check the help120$ python main.py --help121122Usage: main.py [OPTIONS] [NAME]123124Options: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.128```129130</div>131132!!! tip133 Notice that `NAME` is still a *CLI argument*, it's shown up there in the "`Usage: main.py` ...".134135 Also notice that now `[NAME]` has brackets ("`[`" and "`]`") around (before it was just `NAME`) to denote that it's **optional**, not **required**.136137Now run it and test it:138139<div class="termy">140141```console142// With no CLI argument143$ python main.py144145Hello World!146147// With one optional CLI argument148$ python main.py Camila149150Hello Camila151```152153</div>154155!!! tip156 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.157158## An optional *CLI argument* with a default159160We can also make a *CLI argument* have a default value other than `None`:161162```Python hl_lines="4"163{!./src/arguments/tutorial003.py!}164```165166And test it:167168<div class="termy">169170```console171// With no optional CLI argument172$ python main.py173174Hello Wade Wilson175176// With one CLI argument177$ python main.py Camila178179Hello Camila180```181182</div>183184## About *CLI arguments* help185186*CLI arguments* are commonly used for the most necessary things in a program.187188They are normally required and, when present, they are normally the main subject of whatever the command is doing.189190For that reason, Typer (actually Click underneath) doesn't attempt to automatically document *CLI arguments*.191192And you should document them as part of the CLI app 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>.193194Check the last example from the [First Steps](first-steps.md#document-your-cli-app){.internal-link target=_blank}:195196```Python hl_lines="5 6 7 8 9"197{!./src/first_steps/tutorial006.py!}198```199200Here the *CLI argument* `NAME` is documented as part of the help text.201202You should document your *CLI arguments* the same way.203204## Other uses205206`typer.Argument()` has several other use cases. Such as for data validation, to enable other features, etc.207208You will see about these use cases later in the docs.
modified:docs/tutorial/first-steps.md+27 added-13 removed
73 unmodified lines
7475$ python main.py7677// If you run it without the argument, it shows a nice error7878Usage: main.py [OPTIONS] NAME79Try "main.py --help" for help.8081Error: Missing argument 'NAME'.
33 unmodified lines
115$ python main.py --help116117Usage: main.py [OPTIONS] NAME LASTNAME118119Arguments:120 NAME [required]121 LASTNAME [required]122123Options:124 --install-completion Install completion for the current shell.125 --show-completion Show completion for the current shell, to copy it or customize the installation.121 --help Show this message and exit.126 --help Show this message and exit.127128// There are now 2 CLI arguments, name and lastname129130// Now pass a single name argument
103 unmodified lines
234$ python main.py --help235236Usage: main.py [OPTIONS] NAME LASTNAME237238Arguments:239 NAME [required]240 LASTNAME [required]241242Options:234 --formal / --no-formal243 --formal / --no-formal [default: False]244 --install-completion Install completion for the current shell.245 --show-completion Show completion for the current shell, to copy it or customize the installation.246 --help Show this message and exit.247```248249</div>
43 unmodified lines
293$ python main.py --help294295Usage: main.py [OPTIONS] NAME296297Arguments:298 NAME [required]299300Options:287 --lastname TEXT288 --formal / --no-formal301 --lastname TEXT [default: ]302 --formal / --no-formal [default: False]303 --install-completion Install completion for the current shell.304 --show-completion Show completion for the current shell, to copy it or customize the installation.305 --help Show this message and exit.306```307308</div>
29 unmodified lines
338```console339$ python main.py --lastname Gutiérrez Camila340341// and it will still work normally326342Hello Camila Gutiérrez343```344345</div>
18 unmodified lines
364 Say hi to NAME, optionally with a --lastname.365366 If --formal is used, say hi very formally.367368Arguments:369 NAME [required]370371Options:354 --lastname TEXT355 --formal / --no-formal372 --lastname TEXT [default: ]373 --formal / --no-formal [default: False]374 --install-completion Install completion for the current shell.375 --show-completion Show completion for the current shell, to copy it or customize the installation.376 --help Show this message and exit.377```378379</div>380381!!! tip364 You should document the *CLI arguments* in the docstring.382 There is another place to document the specific *CLI options* and *CLI arguments* 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.383366 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.367368 But *CLI arguments* are normally used for the most necessary things, so you should document them here in the *docstring*.369384## Arguments, options, parameters, optional, required385386Be 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.387
104 unmodified lines
modified:docs/tutorial/index.md+4 added-2 removed
5 unmodified lines
67In short (very short), you can declare a function with parameters like:89```Python10from typing import Optional1110def type_example(name: str, formal: bool = False, intro: str = None):12def type_example(name: str, formal: bool = False, intro: Optional[str] = None):13 pass14```1516And your editor (and **Typer**) will know that:1718* `name` is of type `str` and is a required parameter.19* `formal` is a `bool` and is by default `False`.18* `intro` is a `str`, and by default is `None`, so it's optional.20* `intro` is an optional `str`, by default is `None`.2122These type hints are what give you autocomplete in your editor and several other features.2324**Typer** is based on these type hints.
54 unmodified lines
modified:docs/index.md+10 added-1 removed
97 unmodified lines
98$ python main.py --help99100Usage: main.py [OPTIONS] NAME101102Arguments:103 NAME [required]104105Options:106 --install-completion Install completion for the current shell.107 --show-completion Show completion for the current shell, to copy it or customize the installation.108 --help Show this message and exit.
80 unmodified lines
189$ python main.py hello --help190191Usage: main.py hello [OPTIONS] NAME192193Arguments:194 NAME [required]195196Options:197 --help Show this message and exit.198199// And now get the --help for goodbye
1 unmodified line
201$ python main.py goodbye --help202203Usage: main.py goodbye [OPTIONS] NAME204205Arguments:206 NAME [required]207208Options:200 --formal / --no-formal209 --formal / --no-formal [default: False]210 --help Show this message and exit.211212// Automatic --formal and --no-formal for the bool option 🎉213
81 unmodified lines
added:tests/test_tutorial/test_arguments/test_default/__init__.py
added:tests/test_tutorial/test_arguments/test_default/test_tutorial001.py+41 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments.default 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 "[OPTIONS] [NAME]" in result.output18 assert "Arguments:" in result.output19 assert "[default: Wade Wilson]" in result.output202122def test_call_no_arg():23 result = runner.invoke(app)24 assert result.exit_code == 025 assert "Hello Wade Wilson" in result.output262728def test_call_arg():29 result = runner.invoke(app, ["Camila"])30 assert result.exit_code == 031 assert "Hello Camila" 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_arguments/test_default/test_tutorial002.py+43 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments.default 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.output18 assert "Arguments:" in result.output19 assert "[default: (dynamic)]" in result.output202122def test_call_no_arg():23 greetings = ["Hello Deadpool", "Hello Rick", "Hello Morty", "Hello Hiro"]24 for i in range(3):25 result = runner.invoke(app)26 assert result.exit_code == 027 assert any(greet in result.output for greet in greetings)282930def test_call_arg():31 result = runner.invoke(app, ["Camila"])32 assert result.exit_code == 033 assert "Hello Camila" in result.output343536def test_script():37 result = subprocess.run(38 ["coverage", "run", mod.__file__, "--help"],39 stdout=subprocess.PIPE,40 stderr=subprocess.PIPE,41 encoding="utf-8",42 )43 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_envvar/__init__.py
added:tests/test_tutorial/test_arguments/test_envvar/test_tutorial001.py+47 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments.envvar 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 "[OPTIONS] [NAME]" in result.output18 assert "Arguments:" in result.output19 assert "[env var: AWESOME_NAME;default: World]" in result.output202122def test_call_arg():23 result = runner.invoke(app, ["Wednesday"])24 assert result.exit_code == 025 assert "Hello Mr. Wednesday" in result.output262728def test_call_env_var():29 result = runner.invoke(app, env={"AWESOME_NAME": "Wednesday"})30 assert result.exit_code == 031 assert "Hello Mr. Wednesday" in result.output323334def test_call_env_var_arg():35 result = runner.invoke(app, ["Czernobog"], env={"AWESOME_NAME": "Wednesday"})36 assert result.exit_code == 037 assert "Hello Mr. Czernobog" in result.output383940def test_script():41 result = subprocess.run(42 ["coverage", "run", mod.__file__, "--help"],43 stdout=subprocess.PIPE,44 stderr=subprocess.PIPE,45 encoding="utf-8",46 )47 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_envvar/test_tutorial002.py+47 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments.envvar 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.output18 assert "Arguments:" in result.output19 assert "[env var: AWESOME_NAME, GOD_NAME;default: World]" in result.output202122def test_call_arg():23 result = runner.invoke(app, ["Wednesday"])24 assert result.exit_code == 025 assert "Hello Mr. Wednesday" in result.output262728def test_call_env_var1():29 result = runner.invoke(app, env={"AWESOME_NAME": "Wednesday"})30 assert result.exit_code == 031 assert "Hello Mr. Wednesday" in result.output323334def test_call_env_var2():35 result = runner.invoke(app, env={"GOD_NAME": "Anubis"})36 assert result.exit_code == 037 assert "Hello Mr. Anubis" in result.output383940def test_script():41 result = subprocess.run(42 ["coverage", "run", mod.__file__, "--help"],43 stdout=subprocess.PIPE,44 stderr=subprocess.PIPE,45 encoding="utf-8",46 )47 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_envvar/test_tutorial003.py+48 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments.envvar 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.output18 assert "Arguments:" in result.output19 assert "[env var: AWESOME_NAME;default: World]" not in result.output20 assert "[default: World]" in result.output212223def test_call_arg():24 result = runner.invoke(app, ["Wednesday"])25 assert result.exit_code == 026 assert "Hello Mr. Wednesday" in result.output272829def test_call_env_var():30 result = runner.invoke(app, env={"AWESOME_NAME": "Wednesday"})31 assert result.exit_code == 032 assert "Hello Mr. Wednesday" in result.output333435def test_call_env_var_arg():36 result = runner.invoke(app, ["Czernobog"], env={"AWESOME_NAME": "Wednesday"})37 assert result.exit_code == 038 assert "Hello Mr. Czernobog" 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_arguments/test_help/__init__.py
added:tests/test_tutorial/test_arguments/test_help/test_tutorial001.py+37 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments.help 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 "[OPTIONS] NAME" in result.output18 assert "Arguments:" in result.output19 assert "NAME" in result.output20 assert "The name of the user to greet" in result.output21 assert "[required]" in result.output222324def test_call_arg():25 result = runner.invoke(app, ["Camila"])26 assert result.exit_code == 027 assert "Hello Camila" in result.output282930def test_script():31 result = subprocess.run(32 ["coverage", "run", mod.__file__, "--help"],33 stdout=subprocess.PIPE,34 stderr=subprocess.PIPE,35 encoding="utf-8",36 )37 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_help/test_tutorial002.py+38 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments.help 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.output18 assert "Say hi to NAME very gently, like Dirk." in result.output19 assert "Arguments:" in result.output20 assert "NAME" in result.output21 assert "The name of the user to greet" in result.output22 assert "[required]" in result.output232425def test_call_arg():26 result = runner.invoke(app, ["Camila"])27 assert result.exit_code == 028 assert "Hello Camila" in result.output293031def test_script():32 result = subprocess.run(33 ["coverage", "run", mod.__file__, "--help"],34 stdout=subprocess.PIPE,35 stderr=subprocess.PIPE,36 encoding="utf-8",37 )38 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_help/test_tutorial003.py+38 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments.help 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.output18 assert "Say hi to NAME very gently, like Dirk." in result.output19 assert "Arguments:" in result.output20 assert "NAME" in result.output21 assert "Who to greet" in result.output22 assert "[default: World]" in result.output232425def test_call_arg():26 result = runner.invoke(app, ["Camila"])27 assert result.exit_code == 028 assert "Hello Camila" in result.output293031def test_script():32 result = subprocess.run(33 ["coverage", "run", mod.__file__, "--help"],34 stdout=subprocess.PIPE,35 stderr=subprocess.PIPE,36 encoding="utf-8",37 )38 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_help/test_tutorial004.py+38 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments.help import tutorial004 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.output18 assert "Say hi to NAME very gently, like Dirk." in result.output19 assert "Arguments:" in result.output20 assert "NAME" in result.output21 assert "Who to greet" in result.output22 assert "[default: World]" not in result.output232425def test_call_arg():26 result = runner.invoke(app, ["Camila"])27 assert result.exit_code == 028 assert "Hello Camila" in result.output293031def test_script():32 result = subprocess.run(33 ["coverage", "run", mod.__file__, "--help"],34 stdout=subprocess.PIPE,35 stderr=subprocess.PIPE,36 encoding="utf-8",37 )38 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_help/test_tutorial005.py+36 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments.help import tutorial005 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.output18 assert "Arguments:" in result.output19 assert "Who to greet" in result.output20 assert "[default: (Deadpoolio the amazing's name)]" in result.output212223def test_call_arg():24 result = runner.invoke(app, ["Camila"])25 assert result.exit_code == 026 assert "Hello Camila" in result.output272829def test_script():30 result = subprocess.run(31 ["coverage", "run", mod.__file__, "--help"],32 stdout=subprocess.PIPE,33 stderr=subprocess.PIPE,34 encoding="utf-8",35 )36 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_help/test_tutorial006.py+36 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments.help 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 "[OPTIONS] ✨username✨" in result.output18 assert "Arguments:" in result.output19 assert "✨username✨" in result.output20 assert "[default: World]" in result.output212223def test_call_arg():24 result = runner.invoke(app, ["Camila"])25 assert result.exit_code == 026 assert "Hello Camila" in result.output272829def test_script():30 result = subprocess.run(31 ["coverage", "run", mod.__file__, "--help"],32 stdout=subprocess.PIPE,33 stderr=subprocess.PIPE,34 encoding="utf-8",35 )36 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_help/test_tutorial007.py+36 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments.help import tutorial007 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.output18 assert "Say hi to NAME very gently, like Dirk." in result.output19 assert "Arguments:" not in result.output20 assert "[default: World]" not in result.output212223def test_call_arg():24 result = runner.invoke(app, ["Camila"])25 assert result.exit_code == 026 assert "Hello Camila" in result.output272829def test_script():30 result = subprocess.run(31 ["coverage", "run", mod.__file__, "--help"],32 stdout=subprocess.PIPE,33 stderr=subprocess.PIPE,34 encoding="utf-8",35 )36 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_optional/__init__.py
added:tests/test_tutorial/test_arguments/test_optional/test_tutorial001.py+33 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments.optional 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_optional/test_tutorial002.py+39 added
1import subprocess23import typer4from typer.testing import CliRunner56from arguments.optional 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
deleted:tests/test_tutorial/test_arguments/test_tutorial001.py-33 removed
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
deleted:tests/test_tutorial/test_arguments/test_tutorial002.py-39 removed
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
deleted:tests/test_tutorial/test_arguments/test_tutorial003.py-39 removed
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:tests/test_tutorial/test_first_steps/test_tutorial004.py+9 added
9 unmodified lines
10app = typer.Typer()11app.command()(mod.main)121314def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "Arguments:" in result.output18 assert "NAME [required]" in result.output19 assert "LASTNAME [required]" in result.output20 assert "--formal / --no-formal" in result.output212223def test_1():24 result = runner.invoke(app, ["Camila", "Gutiérrez"])25 assert result.exit_code == 026 assert "Hello Camila Gutiérrez" in result.output
28 unmodified lines
modified:tests/test_tutorial/test_first_steps/test_tutorial005.py+2 added
12 unmodified lines
1314def test_help():15 result = runner.invoke(app, ["--help"])16 assert result.exit_code == 017 assert "Arguments:" in result.output18 assert "NAME [required]" in result.output19 assert "--lastname TEXT" in result.output20 assert "--formal / --no-formal" in result.output2122
32 unmodified lines
added:tests/test_tutorial/test_multiple_values/test_arguments_with_multiple_values/test_tutorial002.py+50 added
1import subprocess23import typer4from typer.testing import CliRunner56from multiple_values.arguments_with_multiple_values import tutorial002 as mod78runner = CliRunner()9app = typer.Typer()10app.command()(mod.main)111213def test_help():14 result = runner.invoke(app, ["--help"])15 assert result.exit_code == 016 assert "[OPTIONS] [NAMES]..." in result.output17 assert "Arguments:" in result.output18 assert "[default: Harry, Hermione, Ron]" in result.output192021def test_defaults():22 result = runner.invoke(app)23 assert result.exit_code == 024 assert "Hello Harry" in result.output25 assert "Hello Hermione" in result.output26 assert "Hello Ron" in result.output272829def test_invalid_args():30 result = runner.invoke(app, ["Draco", "Hagrid"])31 assert result.exit_code != 032 assert "Error: argument names takes 3 values" in result.stdout333435def test_valid_args():36 result = runner.invoke(app, ["Draco", "Hagrid", "Dobby"])37 assert result.exit_code == 038 assert "Hello Draco" in result.stdout39 assert "Hello Hagrid" in result.stdout40 assert "Hello Dobby" in result.stdout414243def 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
modified:tests/test_tutorial/test_options/test_help/test_tutorial002.py+1 added-1 removed
19 unmodified lines
20def 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.output24 assert "[default: Wade Wilson]" not in result.output252627def test_script():28 result = subprocess.run(
6 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_datetime/test_tutorial001.py+1 added-1 removed
26 unmodified lines
27def test_invalid():28 result = runner.invoke(app, ["july-19-1989"])29 assert result.exit_code != 030 assert (31 "Error: Invalid value for '[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]': invalid datetime format: july-19-1989. (choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)"31 "Error: Invalid value for 'BIRTH:[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]': invalid datetime format: july-19-1989. (choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)"32 in result.output33 )3435
8 unmodified lines
added:typer/core.py+119 added
1import inspect2from typing import Any, Callable, List, Optional, Tuple, Union34import click.core567class TyperArgument(click.core.Argument):8 def __init__(9 self,10 *,11 # Parameter12 param_decls: List[str],13 type: Optional[Any] = None,14 required: Optional[bool] = None,15 default: Optional[Any] = None,16 callback: Optional[Callable] = None,17 nargs: Optional[int] = None,18 metavar: Optional[str] = None,19 expose_value: bool = True,20 is_eager: bool = False,21 envvar: Optional[Union[str, List[str]]] = None,22 autocompletion: Optional[Callable] = None,23 # TyperArgument24 show_default: Union[bool, str] = True,25 show_choices: bool = True,26 show_envvar: bool = True,27 help: Optional[str] = None,28 hidden: bool = False,29 ):30 self.help = help31 self.show_default = show_default32 self.show_choices = show_choices33 self.show_envvar = show_envvar34 self.hidden = hidden35 super().__init__(36 param_decls=param_decls,37 type=type,38 required=required,39 default=default,40 callback=callback,41 nargs=nargs,42 metavar=metavar,43 expose_value=expose_value,44 is_eager=is_eager,45 envvar=envvar,46 autocompletion=autocompletion,47 )4849 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]: # type: ignore50 # Modified version of click.core.Option.get_help_record()51 # to support Arguments52 if self.hidden:53 return None54 name = self.make_metavar()55 help = self.help or ""56 extra = []57 if self.show_envvar:58 envvar = self.envvar59 # allow_from_autoenv is currently not supported in Typer for CLI Arguments60 if envvar is not None:61 var_str = (62 ", ".join(str(d) for d in envvar)63 if isinstance(envvar, (list, tuple))64 else envvar65 )66 extra.append(f"env var: {var_str}")67 if self.default is not None and (self.show_default or ctx.show_default): # type: ignore68 if isinstance(self.show_default, str):69 default_string = f"({self.show_default})"70 elif isinstance(self.default, (list, tuple)):71 default_string = ", ".join(str(d) for d in self.default)72 elif inspect.isfunction(self.default):73 default_string = "(dynamic)"74 else:75 default_string = self.default76 extra.append(f"default: {default_string}")77 if self.required:78 extra.append("required")79 if extra:80 extra_str = ";".join(extra)81 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"82 return name, help8384 def make_metavar(self) -> str:85 # Modified version of click.core.Argument.make_metavar()86 # to include Argument name87 if self.metavar is not None:88 return self.metavar89 var = self.name.upper()90 if not self.required:91 var = "[{}]".format(var)92 type_var = self.type.get_metavar(self)93 if type_var:94 var += f":{type_var}"95 if self.nargs != 1:96 var += "..."97 return var9899100class TyperCommand(click.core.Command):101 def format_options(102 self, ctx: click.Context, formatter: click.HelpFormatter103 ) -> None:104 args = []105 opts = []106 for param in self.get_params(ctx):107 rv = param.get_help_record(ctx)108 if rv is not None:109 if param.param_type_name == "argument":110 args.append(rv)111 elif param.param_type_name == "option":112 opts.append(rv)113114 if args:115 with formatter.section("Arguments"):116 formatter.write_dl(args)117 if opts:118 with formatter.section("Options"):119 formatter.write_dl(opts)
modified:typer/main.py+11 added-4 removed
7 unmodified lines
89import click1011from .completion import get_completion_inspect_parameters12from .core import TyperArgument, TyperCommand13from .models import (14 AnyType,15 ArgumentInfo,16 CommandFunctionType,
125 unmodified lines
142 hidden: bool = False,143 deprecated: bool = False,144 ) -> Callable[[CommandFunctionType], CommandFunctionType]:145 if cls is None:145 cls = click.Command146 cls = TyperCommand147148 def decorator(f: CommandFunctionType) -> CommandFunctionType:149 self.registered_commands.append(150 CommandInfo(
269 unmodified lines
420 params,421 convertors,422 context_param_name,423 ) = get_params_convertors_ctx_param_name_from_function(command_info.callback)423 cls = command_info.cls or click.Command424 cls = command_info.cls or TyperCommand425 command = cls( # type: ignore426 name=name,427 context_settings=command_info.context_settings,428 callback=get_callback(
256 unmodified lines
685 return (686 click.Option(687 # Option688 param_decls=param_decls,688 show_default=parameter_info.show_default,689 show_default=parameter_info.show_default, # type: ignore690 prompt=parameter_info.prompt,691 confirmation_prompt=parameter_info.confirmation_prompt,692 hide_input=parameter_info.hide_input,693 is_flag=is_flag,
25 unmodified lines
719 nargs = None720 if is_list:721 nargs = -1722 return (722 click.Argument(723 TyperArgument(724 # Argument725 param_decls=param_decls,726 type=parameter_type,727 required=required,728 nargs=nargs,729 # TyperArgument730 show_default=parameter_info.show_default,731 show_choices=parameter_info.show_choices,732 show_envvar=parameter_info.show_envvar,733 help=parameter_info.help,734 hidden=parameter_info.hidden,735 # Parameter736 default=default_value,737 callback=get_param_callback(738 callback=parameter_info.callback, convertor=convertor
117 unmodified lines
modified:typer/models.py+32 added-7 removed
163 unmodified lines
164 expose_value: bool = True,165 is_eager: bool = False,166 envvar: Optional[Union[str, List[str]]] = None,167 autocompletion: Optional[Callable] = None,168 # TyperArgument169 show_default: Union[bool, str] = True,170 show_choices: bool = True,171 show_envvar: bool = True,172 help: Optional[str] = None,173 hidden: bool = False,174 # Choice175 case_sensitive: bool = True,176 # Numbers177 min: Optional[Union[int, float]] = None,
24 unmodified lines
202 self.expose_value = expose_value203 self.is_eager = is_eager204 self.envvar = envvar205 self.autocompletion = autocompletion206 # TyperArgument207 self.show_default = show_default208 self.show_choices = show_choices209 self.show_envvar = show_envvar210 self.help = help211 self.hidden = hidden212 # Choice213 self.case_sensitive = case_sensitive214 # Numbers215 self.min = min
31 unmodified lines
247 is_eager: bool = False,248 envvar: Optional[Union[str, List[str]]] = None,249 autocompletion: Optional[Callable] = None,250 # Option239 show_default: bool = False,251 show_default: bool = True,252 prompt: Union[bool, str] = False,253 confirmation_prompt: bool = False,254 hide_input: bool = False,255 is_flag: Optional[bool] = None,
2 unmodified lines
258 allow_from_autoenv: bool = True,259 help: Optional[str] = None,260 hidden: bool = False,261 show_choices: bool = True,250 show_envvar: bool = False,262 show_envvar: bool = True,263 # Choice264 case_sensitive: bool = True,265 # Numbers266 min: Optional[Union[int, float]] = None,
25 unmodified lines
292 expose_value=expose_value,293 is_eager=is_eager,294 envvar=envvar,295 autocompletion=autocompletion,296 # TyperArgument297 show_default=show_default,298 show_choices=show_choices,299 show_envvar=show_envvar,300 help=help,301 hidden=hidden,302 # Choice303 case_sensitive=case_sensitive,304 # Numbers305 min=min,
16 unmodified lines
322 resolve_path=resolve_path,323 allow_dash=allow_dash,324 path_type=path_type,325 )308 self.show_default = show_default326 self.prompt = prompt327 self.confirmation_prompt = confirmation_prompt328 self.hide_input = hide_input329 self.is_flag = is_flag330 self.flag_value = flag_value331 self.count = count332 self.allow_from_autoenv = allow_from_autoenv316 self.help = help317 self.hidden = hidden318 self.show_choices = show_choices319 self.show_envvar = show_envvar333334335class ArgumentInfo(ParameterInfo):336 def __init__(
7 unmodified lines
344 expose_value: bool = True,345 is_eager: bool = False,346 envvar: Optional[Union[str, List[str]]] = None,347 autocompletion: Optional[Callable] = None,348 # TyperArgument349 show_default: Union[bool, str] = True,350 show_choices: bool = True,351 show_envvar: bool = True,352 help: Optional[str] = None,353 hidden: bool = False,354 # Choice355 case_sensitive: bool = True,356 # Numbers357 min: Optional[Union[int, float]] = None,
25 unmodified lines
383 expose_value=expose_value,384 is_eager=is_eager,385 envvar=envvar,386 autocompletion=autocompletion,387 # TyperArgument388 show_default=show_default,389 show_choices=show_choices,390 show_envvar=show_envvar,391 help=help,392 hidden=hidden,393 # Choice394 case_sensitive=case_sensitive,395 # Numbers396 min=min,
35 unmodified lines
modified:typer/params.py+14 added-2 removed
12 unmodified lines
13 is_eager: bool = False,14 envvar: Optional[Union[str, List[str]]] = None,15 autocompletion: Optional[Callable] = None,16 # Option17 show_default: bool = False,17 show_default: bool = True,18 prompt: Union[bool, str] = False,19 confirmation_prompt: bool = False,20 hide_input: bool = False,21 is_flag: Optional[bool] = None,
2 unmodified lines
24 allow_from_autoenv: bool = True,25 help: Optional[str] = None,26 hidden: bool = False,27 show_choices: bool = True,28 show_envvar: bool = False,28 show_envvar: bool = True,29 # Choice30 case_sensitive: bool = True,31 # Numbers32 min: Optional[Union[int, float]] = None,
75 unmodified lines
108 expose_value: bool = True,109 is_eager: bool = False,110 envvar: Optional[Union[str, List[str]]] = None,111 autocompletion: Optional[Callable] = None,112 # TyperArgument113 show_default: Union[bool, str] = True,114 show_choices: bool = True,115 show_envvar: bool = True,116 help: Optional[str] = None,117 hidden: bool = False,118 # Choice119 case_sensitive: bool = True,120 # Numbers121 min: Optional[Union[int, float]] = None,
28 unmodified lines
150 expose_value=expose_value,151 is_eager=is_eager,152 envvar=envvar,153 autocompletion=autocompletion,154 # TyperArgument155 show_default=show_default,156 show_choices=show_choices,157 show_envvar=show_envvar,158 help=help,159 hidden=hidden,160 # Choice161 case_sensitive=case_sensitive,162 # Numbers163 min=min,
20 unmodified lines
modified:mkdocs.yml+7 added-1 removed
25 unmodified lines
26 - Tutorial - User Guide - Intro: 'tutorial/index.md'27 - First Steps: 'tutorial/first-steps.md'28 - Printing and Colors: 'tutorial/printing.md'29 - Terminating: 'tutorial/terminating.md'30 - CLI Arguments: 'tutorial/arguments.md'30 - CLI Arguments:31 - CLI Arguments Intro: 'tutorial/arguments/index.md'32 - Optional CLI Arguments: 'tutorial/arguments/optional.md'33 - CLI Arguments with Default: 'tutorial/arguments/default.md'34 - CLI Arguments with Help: 'tutorial/arguments/help.md'35 - CLI Arguments with Environment Variables: 'tutorial/arguments/envvar.md'36 - Other uses: 'tutorial/arguments/other-uses.md'37 - CLI Options:38 - CLI Options Intro: 'tutorial/options/index.md'39 - CLI Options with Help: 'tutorial/options/help.md'40 - Required CLI Options: 'tutorial/options/required.md'
89 unmodified lines
modified:README.md+10 added-1 removed
97 unmodified lines
98$ python main.py --help99100Usage: main.py [OPTIONS] NAME101102Arguments:103 NAME [required]104105Options:106 --install-completion Install completion for the current shell.107 --show-completion Show completion for the current shell, to copy it or customize the installation.108 --help Show this message and exit.
80 unmodified lines
189$ python main.py hello --help190191Usage: main.py hello [OPTIONS] NAME192193Arguments:194 NAME [required]195196Options:197 --help Show this message and exit.198199// And now get the --help for goodbye
1 unmodified line
201$ python main.py goodbye --help202203Usage: main.py goodbye [OPTIONS] NAME204205Arguments:206 NAME [required]207208Options:200 --formal / --no-formal209 --formal / --no-formal [default: False]210 --help Show this message and exit.211212// Automatic --formal and --no-formal for the bool option 🎉213
81 unmodified lines