:memo: :sparkles: :bug: Add docs for CLI parameters with multiple values, with tests and bug fixes
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 ff37cb8, c84fcae · Browse files · 17 files·+417 added−5 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
17 files+417 added−5 removed
- tests:+155 added−0 removed
- other:+262 added−5 removed
Provenance
- Commit
bcdcfce- Tree
9dd82cb- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
ff37cb8- Parent 2
c84fcae
17 files changed+417 added−5 removed
added:docs/src/multiple_values/arguments_with_multiple_values/tutorial001.py+15 added
1+from pathlib import Path2+from typing import List3+4+import typer5+6+7+def main(files: List[Path], celebration: str):8+ for path in files:9+ if path.is_file():10+ typer.echo(f"This file exists: {path.name}")11+ typer.echo(celebration)12+13+14+if __name__ == "__main__":15+ typer.run(main)added:docs/src/multiple_values/multiple_options/tutorial001.py+15 added
1+from typing import List2+3+import typer4+5+6+def main(user: List[str] = typer.Option(None)):7+ if not user:8+ typer.echo("No provided users")9+ raise typer.Abort()10+ for u in user:11+ typer.echo(f"Processing user: {u}")12+13+14+if __name__ == "__main__":15+ typer.run(main)added:docs/src/multiple_values/multiple_options/tutorial002.py+11 added
1+from typing import List2+3+import typer4+5+6+def main(number: List[float] = typer.Option([])):7+ typer.echo(f"The sum is {sum(number)}")8+9+10+if __name__ == "__main__":11+ typer.run(main)added:docs/src/multiple_values/options_with_multiple_values/tutorial001.py+17 added
1+from typing import Tuple2+3+import typer4+5+6+def main(user: Tuple[str, int, bool] = typer.Option((None, None, None))):7+ username, coins, is_wizard = user8+ if not username:9+ typer.echo("No user provided")10+ raise typer.Abort()11+ typer.echo(f"The username {username} has {coins} coins")12+ if is_wizard:13+ typer.echo("And this user is a wizard!")14+15+16+if __name__ == "__main__":17+ typer.run(main)added:docs/tutorial/multiple-values/arguments-with-multiple-values.md+28 added
12345678910111213141516171819202122232425262728*CLI arguments* can also receive multiple values.
You can define the type of a *CLI argument* using `typing.List`.
```Python hl_lines="7"{!./src/multiple_values/arguments_with_multiple_values/tutorial001.py!}```
And then you can pass it as many *CLI arguments* of that type as you want:
<div class="termy">
```console$ python main.py ./index.md ./first-steps.md woohoo!
This file exists: index.mdwoohoo!This file exists: first-steps.mdwoohoo!```
</div>
!!! tip We also declared a final *CLI argument* `celebration`, and it's correctly used even if we pass an arbitrary number of `files` first.
!!! info 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*.added:docs/tutorial/multiple-values/index.md+3 added
123There are several ways to declare multiple values for *CLI options* and *CLI arguments*.
We'll see them in the next short sections.added:docs/tutorial/multiple-values/multiple-options.md+66 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566You can declare a *CLI option* that can be used multiple times, and then get all the values.
For example, let's say you want to accept several users in a single execution.
For this, use the standard Python `typing.List` to declare it as a `list` of `str`:
```Python hl_lines="1 6"{!./src/multiple_values/multiple_options/tutorial001.py!}```
You will receive the values as you declared them, as a `list` of `str`.
Check it:
<div class="termy">
```console$ python main.py
No provided usersAborted!
// Now pass a user$ python main.py --user Camila
Processing user: Camila
// And now try with several users$ python main.py --user Camila --user Rick --user Morty
Processing user: CamilaProcessing user: RickProcessing user: Morty```
</div>
## Multiple `float`
The same way, you can use other types and they will be converted by **Typer** to their declared type:
```Python hl_lines="6"{!./src/multiple_values/multiple_options/tutorial002.py!}```
Check it:
<div class="termy">
```console$ python main.py
The sum is 0
// Try with some numbers$ python main.py --number 2
The sum is 2.0
// Try with some numbers$ python main.py --number 2 --number 3 --number 4.5
The sum is 9.5```
</div>added:docs/tutorial/multiple-values/options-with-multiple-values.md+92 added
1+You can also declare a *CLI option* that takes several values of different types.2+3+You can set the number of values and types to anything you want, but it has to be a fixed number of values.4+5+For this, use the standard Python `typing.Tuple`:6+7+```Python hl_lines="1 6"8+{!./src/multiple_values/options_with_multiple_values/tutorial001.py!}9+```10+11+Each of the internal types defines the type of each value in the tuple.12+13+So:14+15+```Python16+user: Tuple[str, int, bool]17+```18+19+means that the parameter `user` is a tuple of 3 values.20+21+* The first value is a `str`.22+* The second value is an `int`.23+* The third value is a `bool`.24+25+Later we do:26+27+```Python28+username, coins, is_wizard = user29+```30+31+If you hadn't seen that, it means that `user` is a tuple with 3 values, and we are assigning each of the values to a new variable:32+33+* The first value in the tuple `user` (a `str`) goes to the variable `username`.34+* The second value in the tuple `user` (an `int`) goes to the variable `coins`.35+* The third value in the tuple `user` (a `bool`) goes to the variable `is_wizard`.36+37+So, this:38+39+```Python40+username, coins, is_wizard = user41+```42+43+is equivalent to this:44+45+```Python46+username = user[0]47+coins = user[1]48+is_wizard = user[2]49+```50+51+!!! tip52+ Notice that the default is a tuple with `(None, None, None)`.53+54+ You cannot simply use `None` here as the default because <a href="https://github.com/pallets/click/issues/472" target="_blank">Click doesn't support it</a>.55+56+## Check it57+58+Now let's see how this works in the terminal:59+60+<div class="termy">61+62+```console63+// check the help64+$ python main.py --help65+66+// Notice the <TEXT INTEGER BOOLEAN>67+Usage: main.py [OPTIONS]68+69+Options:70+ --user <TEXT INTEGER BOOLEAN>...71+ --install-completion Install completion for the current shell.72+ --show-completion Show completion for the current shell, to copy it or customize the installation.73+ --help Show this message and exit.74+75+// Now try it76+$ python main.py --user Camila 50 yes77+78+The username Camila has 50 coins79+And this user is a wizard!80+81+// With other values82+$ python main.py --user Morty 3 no83+84+The username Morty has 3 coins85+86+// Try with invalid values (not enough)87+$ python main.py --user Camila 5088+89+Error: --user option requires 3 arguments90+```91+92+</div>added:tests/test_tutorial/test_multiple_values/test_arguments_with_multiple_values/__init__.py
added:tests/test_tutorial/test_multiple_values/test_arguments_with_multiple_values/test_tutorial001.py+27 added
1+import subprocess2+3+import typer4+from typer.testing import CliRunner5+6+from multiple_values.arguments_with_multiple_values import tutorial001 as mod7+8+runner = CliRunner()9+app = typer.Typer()10+app.command()(mod.main)11+12+13+def test_main():14+ result = runner.invoke(app, ["README.md", "pyproject.toml", "woohoo!"])15+ assert result.exit_code == 016+ assert "This file exists: README.md\nwoohoo!" in result.output17+ assert "This file exists: pyproject.toml\nwoohoo!" in result.output18+19+20+def test_script():21+ result = subprocess.run(22+ ["coverage", "run", mod.__file__, "--help"],23+ stdout=subprocess.PIPE,24+ stderr=subprocess.PIPE,25+ encoding="utf-8",26+ )27+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_multiple_values/test_multiple_options/__init__.py
added:tests/test_tutorial/test_multiple_values/test_multiple_options/test_tutorial001.py+43 added
1+import subprocess2+3+import typer4+from typer.testing import CliRunner5+6+from multiple_values.multiple_options import tutorial001 as mod7+8+runner = CliRunner()9+app = typer.Typer()10+app.command()(mod.main)11+12+13+def test_main():14+ result = runner.invoke(app)15+ assert result.exit_code != 016+ assert "No provided users" in result.output17+ assert "Aborted!" in result.output18+19+20+def test_1_user():21+ result = runner.invoke(app, ["--user", "Camila"])22+ assert result.exit_code == 023+ assert "Processing user: Camila" in result.output24+25+26+def test_3_user():27+ result = runner.invoke(28+ app, ["--user", "Camila", "--user", "Rick", "--user", "Morty"]29+ )30+ assert result.exit_code == 031+ assert "Processing user: Camila" in result.output32+ assert "Processing user: Rick" in result.output33+ assert "Processing user: Morty" in result.output34+35+36+def 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.stdoutadded:tests/test_tutorial/test_multiple_values/test_multiple_options/test_tutorial002.py+38 added
1+import subprocess2+3+import typer4+from typer.testing import CliRunner5+6+from multiple_values.multiple_options import tutorial002 as mod7+8+runner = CliRunner()9+app = typer.Typer()10+app.command()(mod.main)11+12+13+def test_main():14+ result = runner.invoke(app)15+ assert result.exit_code == 016+ assert "The sum is 0" in result.output17+18+19+def test_1_number():20+ result = runner.invoke(app, ["--number", "2"])21+ assert result.exit_code == 022+ assert "The sum is 2.0" in result.output23+24+25+def test_2_number():26+ result = runner.invoke(app, ["--number", "2", "--number", "3", "--number", "4.5"])27+ assert result.exit_code == 028+ assert "The sum is 9.5" in result.output29+30+31+def 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.stdoutadded:tests/test_tutorial/test_multiple_values/test_options_with_multiple_values/__init__.py
added:tests/test_tutorial/test_multiple_values/test_options_with_multiple_values/test_tutorial001.py+47 added
1+import subprocess2+3+import typer4+from typer.testing import CliRunner5+6+from multiple_values.options_with_multiple_values import tutorial001 as mod7+8+runner = CliRunner()9+app = typer.Typer()10+app.command()(mod.main)11+12+13+def test_main():14+ result = runner.invoke(app)15+ assert result.exit_code != 016+ assert "No user provided" in result.output17+ assert "Aborted!" in result.output18+19+20+def test_user_1():21+ result = runner.invoke(app, ["--user", "Camila", "50", "yes"])22+ assert result.exit_code == 023+ assert "The username Camila has 50 coins" in result.output24+ assert "And this user is a wizard!" in result.output25+26+27+def test_user_2():28+ result = runner.invoke(app, ["--user", "Morty", "3", "no"])29+ assert result.exit_code == 030+ assert "The username Morty has 3 coins" in result.output31+ assert "And this user is a wizard!" not in result.output32+33+34+def test_invalid_user():35+ result = runner.invoke(app, ["--user", "Camila", "50"])36+ assert result.exit_code != 037+ assert "Error: --user option requires 3 arguments" in result.output38+39+40+def 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.stdoutadded:tests/test_tutorial/test_multiple_values/__init__.py
modified:typer/main.py+15 added-5 removed
460 unmodified lines461 462 return convertor463 464 465+def generate_iter_convertor(convertor: Callable[[Any], Any]) -> Callable:466+ def internal_convertor(value: Any) -> List[Any]:467+ return [convertor(v) for v in value]468+469+ return internal_convertor470+471+472 def get_callback(473 *,474 callback: Optional[Callable] = None,475 params: Sequence[click.Parameter] = [],160 unmodified lines636 origin = getattr(main_type, "__origin__", None)637 # Handle Tuples and Lists638 if lenient_issubclass(origin, List):639 main_type = main_type.__args__[0]633- assert (634- "__origin__" not in main_type640+ assert not getattr(641+ main_type, "__origin__", None642 ), "List types with complex sub-types are not currently supported"643 is_list = True644 elif lenient_issubclass(origin, Tuple): # type: ignore645 types = []639- for type_ in origin.__args__:640- assert (641- "__origin__" not in type_646+ for type_ in main_type.__args__:647+ assert not getattr(648+ type_, "__origin__", None649 ), "Tuple types with complex sub-types are not currently supported"650 types.append(651 get_click_type(annotation=type_, parameter_info=parameter_info)652 )6 unmodified lines659 if lenient_issubclass(main_type, Path):660 convertor = param_path_convertor661 if lenient_issubclass(main_type, Enum):662 convertor = generate_enum_convertor(main_type)663+ if convertor and is_list:664+ convertor = generate_iter_convertor(convertor)665+ # TODO: handle recursive conversion for tuples666 if isinstance(parameter_info, OptionInfo):667 if main_type is bool and not (parameter_info.is_flag is False):668 is_flag = True669 # Click doesn't accept a flag of type bool, only None, and then it sets it74 unmodified lines